JDBC(一)

工具类代码
 
public class JDBCUtil {
	private static String driverClassName;
	private static String url;
	private static String userName;
	private static String password;
	static{
//jdbc.properties配置文件放在类路径下
		InputStream in=JDBCUtil.class.getClassLoader().getSystemResourceAsStream("jdbc.properties");
		Properties prop= new Properties();
		try {
			prop.load(in);
			driverClassName=(String) prop.get("driverClassName");
			url=prop.getProperty("url");
			userName=prop.getProperty("username");
			password=prop.getProperty("password");
			Class.forName(driverClassName);
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
	public static Connection getConnection() throws SQLException{
		Connection conn=DriverManager.getConnection(url, userName, password);
		return conn;
	}
	public static void release(Connection conn,Statement stmt,ResultSet rs){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			rs=null;			
		}
		if(stmt!=null){
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			stmt=null;
		}
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			conn=null;
		}
		
		
		
	}

}

批处理代码:

public class JdbcDemo1 {

	public static void main(String[] args) throws FileNotFoundException  {
		test2();	
	}
 public static void test1(){
	//利用PreparedStatement批量发送处理语句:只能执行一条sql语句
	 Connection conn=null;
		PreparedStatement stmt=null;
		ResultSet rs=null;
	 try {
			conn=JDBCUtil.getConnection();
			String sql="insert into batchtest (id,name) values(?,?)";
			stmt=conn.prepareStatement(sql);
			for(int i=0;i<10000000;i++){
				stmt.setInt(1, i);
				stmt.setString(2, "a"+i);
				stmt.addBatch();
				if(i%1000==0){	
					//可以有效的防止内存溢出
				stmt.executeBatch();
				stmt.clearBatch();
				}
			}
			stmt.executeBatch();//执行尾数
		    
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JDBCUtil.release(conn, stmt, rs);
		}
 }
 public static void test2(){
	//利用Statement批量发送处理语句:多条
	 Connection conn=null;
	 Statement stmt=null;
	 ResultSet rs=null;
	 try {
		conn=JDBCUtil.getConnection();
		stmt=conn.createStatement();
		String sql1="insert into batchtest (id,name) values(1,'a')";
		String sql2="insert into batchtest (id,name) values(2,'w')";
		String sql3="delete from batchtest where id=1";
		stmt.addBatch(sql1);
		stmt.addBatch(sql2);
		stmt.addBatch(sql3);
		stmt.executeBatch();
	} catch (SQLException e) {
		e.printStackTrace();
	}finally{
		JDBCUtil.release(conn, stmt, rs);
	}
	 
 }
 }



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值