首先我们需要建立一个线程类,继承Thread类,并实现run方法
1、获取数据库连接
2、编写插入的sql语句
3、关闭自动提交conn.setAutoCommit(false);
4、编写for循环,跟着那个的插入方法一样。
5、将注入的信息,一条条添加到pst中。pst.addBatch();//批量添加信息
6、在for循环结束的地方,将信息批量执行。pst.executeBatch();
7、提交事务mit();
public class InsertThread extends Thread {public void run(){String url = "jdbc:postgresql://localhost:5432/teacher"; //数据库连接地址String name = "org.postgresql.Driver";String user = "postgres"; String password = "*****";//密码Connection conn = null;try {Class.forName(name);conn=DriverManager.getConnection(url, user, password);conn.setAutoCommit(false);//关闭自动提交} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}long begin=new Date().getTime();String sql= "INSERT INTO teachers (t_name,t_password,sex,description,pic_url,school_name,regist_date,remark) VALUES(?,?,?,?,?,?,?,?)";try {StringBuilder sqls= new StringBuilder(); conn.setAutoCommit(false);PreparedStatement pst=conn.prepareStatement(sql);//编写事务for(int i=1;i<=10;i++){for(int j=1;j<=1000000;j++){pst.setString(1,"teacher122");pst.setString(2, "12223444");pst.setString(3, "男");pst.setString(4, "教师");pst.setString(5, "");pst.setString(6, "java大学");pst.setString(7, "-08-16 14:43:26");pst.setString(8, "你好啊");pst.addBatch();//批量添加信息}// 执行批量操作pst.executeBatch();// 提交事务mit();}pst.close();conn.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 结束时间Long end = new Date().getTime();// 耗时System.out.println("100万条数据插入花费时间 : " + (end - begin) / 1000 + " s"+" 插入完成"); }}
8 编写测试类
public class InsertTest {/*** @param args*/public static void main(String[] args) {for (int i = 1; i <=10; i++) {new InsertThread().start();}}}