String [] queries = {
"INSERT INTO Employee { Eno, Ename, Ecode, EDept} values ('1', 'Allen', 'abc', 'Sales')",
"INSERT INTO Employee { Eno, Ename, Ecode, EDept} values ('2', 'Max', '102', 'Marketing')",
"INSERT INTO Employee { Eno, Ename, Ecode, EDept} values ('3', 'Ward', 'xyz', 'Sales')",
"INSERT INTO Employee { Eno, Ename, Ecode, EDept} values ('4', 'Sam', '55', 'Marketing')",
};
Connection connection = new getConnection();
Statement statement = connection.createStatement();
for (String query : queries ) {
statement.execute(query);
}
statement.close();
connection.close();
这是一个糟糕的代码,在数据库中每一行INSERT语句都需要单独来执行。发送一批INSERT语句到数据库中一气呵成:
import java.sql.Connection;
import java.sql.Statement;
//…
Connection connection = new getConnection();
Statement statement = connection.createStatement();
For (Employee employee: employees){
String query = "INSERT INTO Employee (Eno, Ename, Ecode, Edept) values (' " + Employee. getEno() + "', '" + Employee.getEname() +"', '" + Employee.getEcode() + "', '" + Employee.getEdept() + "')";
statement.addBatch(query);
}
statement. executeBatch();
statement.close();
connection.close();
插入大型数据集时,批处理是非常重要的。为了显著提升性能,程序员应该尽量在批处理模式下运行一条语句。执行批量插入的另外一种方法是使用PreparedStatement对象。然而批处理不仅仅只是局限于INSERT语句,你还可以利用它来执行更新、删除和声明等操作。
844

被折叠的 条评论
为什么被折叠?



