java [30] 使用JDBC批处理功能

需求:向数据库插入多条数据

使用JDBC时,频繁创建链接,传sql语句需要消费大量资源,使用批处理功能解决:

package day820;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Scrollertest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Createbatch();
	}
	public static void Createbatch(){
		Connection conn = null;
		PreparedStatement ps = null; 
		ResultSet rs = null;
		try {
			conn = jdbcUtils.getConnection();
			//3.创建语句
			//查询
			//String sql = "select id,name,passwd,salary from T1 ";
			String sql = "insert into T1(name,passwd,salary,birthday) values(?,?,?,?)";
			ps = conn.prepareStatement(sql);
			
			for (int i=0;i<100;i++){
				ps.setString(1, "nametest"+i);
				ps.setString(2, "passtest"+i);
				ps.setFloat(3, 3000f);
				ps.setDate(4, new Date(System.currentTimeMillis()));
				
				//打包
				ps.addBatch();
			}
			//4.执行语句
			//返回int[]类型。执行了多条
			ps.executeBatch();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
				
		}finally {
			//6.释放资源
			//jdbcUtils.free(rs,st,conn);
			jdbcUtils.free(rs, ps, conn);
		}
		
		
		
	}

}

猜你喜欢

转载自blog.csdn.net/qq_38125626/article/details/81989991
今日推荐