第二十五章 JDBC的批處理功能

執行多條數據,速度較快


package cn.itcast.jdbc;

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

public class BatchTest {
	static void createBatch() throws SQLException
	{
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try{
			conn = JdbcUtils.getConnection();
			String sql = "insert into user(name,birthday,money) values(?,?,?)";
			ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
			for(int i=0; i<10; i++){
				ps.setString(1, "batch name" + i);
				ps.setDate(2, new Date(System.currentTimeMillis()));
				ps.setFloat(3, 100f+i);
				ps.addBatch();
			}
			int[] is = ps.executeBatch();
		}finally{
			JdbcUtils.free(rs, ps, conn);
		}
	}
	public static void main(String[] args){
		try {
			BatchTest.createBatch();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章