需要导入mysql驱动包
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Random;
public class User {
private String url = "jdbc:mysql://localhost:3306/test";
private String user = "root";
private String password = "root";
@org.junit.Test
public void Test(){
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,user,password);
String sql = "INSERT INTO user(Name,Sex,Age,Tel) VALUES(?,?,?,?)";
pstm = conn.prepareStatement(sql);
conn.setAutoCommit(false);
Long startTime = System.currentTimeMillis();
for (int n = 1;n <= 1000;n++){
Random rand = new Random();
for (int i = 1;i <=100000;i++){
int a = rand.nextInt(20);
int b = rand.nextInt(10);
int c = rand.nextInt(10);
int d = rand.nextInt(10);
int upCase = rand.nextInt(26)+65;//得到65-90的随机数
int downCase = rand.nextInt(26)+97;//得到97-122的随机数
String up = String .valueOf((char)upCase);//得到A-Z
String down = String .valueOf((char)downCase);//得到a-z
pstm.setString(1,up+down);
pstm.setString(2,"男");
pstm.setInt(3, a);
pstm.setInt(4, a+5+b+c+2+d);
pstm.addBatch();
}
pstm.executeBatch();
conn.commit();
System.out.println("已经存入"+n*100000+"条");
}
Long endTime = System.currentTimeMillis();
System.out.println("用时"+(endTime-startTime));
} catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
} finally{
if(pstm != null){
try{
pstm.close();
} catch(SQLException e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
if(conn != null){
try{conn.close();
} catch(SQLException e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
public static void main(String[] args) {
User u = new User();
u.Test();
}
}