package com.test.demo.autodemo;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import java.sql.*;
import java.util.Random;
public class TestInsert {
private Stringurl ="jdbc:mysql://localhost:3306/test01";
private Stringuser ="root";
private Stringpassword ="123456";
//创建数据库连接
static Connectionconn =null;
//创建预编译语句对象
static PreparedStatementpstmt =null;
//创建一个结果集
static ResultSetresult =null;
/**
* 初始化数据库连接驱动
*/
private static void initJdbc() {
try {
Class.forName("com.mysql.jdbc.Driver"); //加载驱动程序
String url ="jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8"; //数据库连接信息
String user ="root"; //数据库用户名
String pass ="666888"; //数据库密码
conn = DriverManager.getConnection(url, user, pass); //获取连接
System.out.println("linked successfully");
}catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
}
public static void Test()throws SQLException {
String sql ="INSERT INTO demo(aaa,bbb,ccc,name,action) VALUES(?,?,?,CONCAT('name',?),?)";
pstmt=conn.prepareStatement(sql);
Long startTime= System.currentTimeMillis();
Random random=new Random();
int a;
for(int i=1;i<=3;i++){
a=random.nextInt(10);
String a1="a"+i;
String b1="b"+i;
String c1="c"+i;
pstmt.setString(1,a1);
pstmt.setString(2,b1);
pstmt.setString(3,c1);
pstmt.setInt(4,i);
pstmt.setString(5,"D");
pstmt.execute();
}
System.out.println("insert data success!");
Long endTime = System.currentTimeMillis();
System.out.println("OK,用时:" + (endTime - startTime));
}
//关闭数据库连接
public static void closeCon(Connection con){
if(con !=null){
try{
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args)throws SQLException {
initJdbc();
Test();
closeCon(conn);
}
}
网友评论