JDBC连接

package com.db; 

import java.sql.*; 

/**
 * 连接sql 
 * @author 赵永恩
 *
 */
public class Jdbc{ 
	
	String dbUrl="jdbc:sqlserver://localhost:1433; DatabaseName=yong"; 
	String theUser="sa"; 
	String thePw=""; 
	Connection c=null; 
	Statement conn; 
	ResultSet rs=null; 
	
public Jdbc(){ 
	try{ 
		Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); 
		c = DriverManager.getConnection(dbUrl,theUser,thePw); 
		//创建滚动结果集 需要把创建stme对象后多加两个参数ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE
		conn=c.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); 
		
	}catch(Exception e){ 
		e.printStackTrace(); 
	} 
} 

/**
 * 更新
 * @param sql
 * @return
 */
public boolean executeUpdate(String sql){ 
	try { 
		conn.executeUpdate(sql); 
		return true; 
	} catch (SQLException e) { 
		e.printStackTrace(); 
		return false; 
	} 
} 




/**
 * 查询
 * @param sql
 * @return
 */
public ResultSet executeQuery(String sql) { 
rs=null; 
	try { 
		rs=conn.executeQuery(sql); 
	} catch (SQLException e) { 
		e.printStackTrace(); 
	} 
		return rs; 
} 


/**
 * 关闭数据库
 */
public void close() { 
	try { 
		conn.close(); 
		c.close(); 
	} catch (Exception e) { 
		e.printStackTrace(); 
	} 
} 

/**
 * 测试
 * @param args
 */
public static void main(String[] args){ 
	Jdbc jdbd_db = new Jdbc(); 
	
	//查询
	ResultSet rs=jdbd_db.executeQuery("select * from dqb"); 
	try{ 
		while (rs.next()) { 	
			System.out.println(rs.getString("dqbid")); 
			System.out.println("ddd"); 
		} 
	}catch(Exception e) { 
		e.printStackTrace(); 
	}finally{
		jdbd_db.close();
	}  
	
	//增加
	//String sql="insert into dqb(dqbid) VALUES('1')";
	//String sql="insert into dqb(dqbid,dqid,dqfid,dqname,dqtype) VALUES('34372','371','34',' 澎湖县','2')";
	//conn.executeUpdate(sql);
	
	//删除
	//String sql="delete from dqb";
	//String sql="delete from dqb where dqbid='343712951' ";
	//conn.executeUpdate(sql);

	} 

} 


你可能感兴趣的:(sql,C++,c,jdbc,C#)