JDBC批量向数据库插入数据(十)

来源:互联网 发布:nga 数据库 编辑:程序博客网 时间:2024/04/30 05:24

重点内容
1.在插入大量数据时,我们使用statement对象,而不用PreparedStatement对象。

2.实例演示

package TestBatch;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import com.mysql.jdbc.Statement;public class TestBatch {    public static void main(String[] args) throws SQLException {        Statement stmt=null;        ResultSet rs=null;        String url ="jdbc:mysql://localhost:3306/test";         String user = "root";         String password = "root";        Connection conn = DriverManager.getConnection(url, user, password);        System.out.println("Successfully connected");        conn.setAutoCommit(false);        long start=System.currentTimeMillis();        stmt=(Statement) conn.createStatement();        for(int i=0;i<30000;i++) {            stmt.addBatch("insert into tb_batch(name,depart,address)value('凯耐"+i+"','部门"+i+"','深圳')");        }        stmt.executeBatch();        long end=System.currentTimeMillis();        System.out.println("插入3万条数据所需时间"+(end-start)+"毫秒");        conn.commit();    }}

数据结果

Successfully connected插入3万条数据所需时间9318毫秒
原创粉丝点击