3.Statement批处理文件
在开发中需要经常向数据库中添加多条数据库语句,逐条加入效率会很低,可以使用Statement进行批处理。Siatement通过addBtch()方法添加一条语句,通过executeBatch方法批量执行sql语句.
3.1 addBtch()方法添加一条语句
package mysql;
import jdbc.utils.Utils;
import java.sql.*;
public class Pichu {
public static void main(String args[]) throws Exception{
/*1.use chapter01;chapter01
* 2.Siatement通过addBtch()方法添加一条语句;
* 3.select * from school;
*/
Connection conn=null;
Statement st=null;
try{//加载数据库驱动
conn=Utils.getConnection();
st=conn.createStatement();
String sql1="DROP TABLE IF EXISTS school";
String sql2="CREATE TABLE school(id int,name varchar(20))";
String sql3="INSERT INTO school VALUES(2,'BIT')";
String sql4="UPDATE school SET id=1";
st.addBatch(sql1);
st.addBatch(sql2);
st.addBatch(sql3);
st.addBatch(sql4);
st.executeBatch();
}catch(SQLException e){
e.printStackTrace();
}finally{
Utils.release(null,st,conn);
}
}
}
运行结果:

本文介绍了一种使用Java中的Statement对象进行SQL批处理的方法,通过addBatch()添加多条SQL语句,并使用executeBatch()一次性执行所有添加的SQL语句,提高了执行效率。
&spm=1001.2101.3001.5002&articleId=73350520&d=1&t=3&u=9cf5e91401b64c31992b51403203de9c)
2万+

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



