一、先建个测试表test CREATE TABLE test ( ZD1 varchar(32) NOT NULL, ZD2 varchar(32) DEFAULT NULL, ZD3 varchar(11) DEFAULT NULL, PRIMARY KEY (ZD1) );
二、导入mysql驱动,脚本如下 package com.company;
import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager;
import java.sql.SQLException; import java.text.SimpleDateFormat;
import com.mysql.jdbc.PreparedStatement;
public class test{ /设置参数/ private static Connection conn = null; /构造方法,链接数据库/ public test() { try{ System.out.println(“正在连接数据库…”); Class.forName(“com.mysql.jdbc.Driver”);//加载mysql驱动程序类 String url = “jdbc:MySQL://192.168.0.47:3306/03base”;//url为连接字符串 String user = “root”;//数据库用户名 String pwd = “root123”;//数据库密码 conn=(Connection)DriverManager.getConnection(url,user,pwd); System.out.println(“数据库连接成功!!!”); }catch(Exception e){ //抛出异常处理 System.out.println(e.getMessage()); e.printStackTrace(); } }
//声明一个公有访问获取系统时间的对象 public static String getStringDate() { Date currentTime = new Date(System.currentTimeMillis()); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); String dateString = formatter.format(currentTime); return dateString; } public static void main(String[] args) throws SQLException { long begin = new Date(System.currentTimeMillis()).getTime(); //开始时间 test a = new test();//实例化对象,作用是调用构造方法 a.getClass();//无意义 String insertsql="INSERT INTO sdgl.test (ZD1,ZD2,ZD3) VALUES"; //批量插入 StringBuffer suffix = new StringBuffer(); conn.setAutoCommit(false); PreparedStatement pst = (PreparedStatement) conn.prepareStatement(""); String ZD1 = "0"; String ZD2 = null; String ZD3 = "sql"; String time = getStringDate(); int random=0; // 外层循环,总提交事务次数 for (int i = 1; i <= 2; i++) { suffix = new StringBuffer(); // 第j次提交步长 for (int j = 1; j <= 10; j++) { random++; ZD1 = time; ZD2 = time; int length=7-(String.valueOf(random)).length(); for(int n=0;n<length;n++){ ZD1=ZD1+"0"; } ZD1=ZD1+random; // 构建SQL后缀 System.out.println(ZD1); suffix.append("('"+ZD1+"','"+ZD2+"','"+ZD3+"'),"); } // 构建完整SQL String sql = insertsql + suffix.substring(0, suffix.length()-1); System.out.println(sql); try { // 添加执行SQL pst.addBatch(sql); pst.executeBatch(); // 提交事务 conn.commit(); } catch (Exception e) { conn.rollback(); } } long end = new Date(System.currentTimeMillis()).getTime(); System.out.println("castime : " + (end - begin) + " ms"); // 关闭链接 pst.close(); conn.close(); }}