mysql批量插⼊增加参数_Mysql批量插⼊提⾼性能通过使⽤addBatch()和executeBatch()这⼀对⽅法可以实现批量处理数据。
⼿动打开mysql批量插⼊的开关,性能才能表现出来,⼤家试试就知道啦。。
加上“?useServerPrepStmts=false&rewriteBatchedStatements=true ”
fcky.demo;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DbStoreHelper {
private String insert_sql;
private String charset;
private boolean debug;
private String connectStr;
private String username;
private String password;
public DbStoreHelper() {
connectStr = "jdbc:mysql://localhost:3306/db_ip";
connectStr += "?useServerPrepStmts=false&rewriteBatchedStatements=true";
insert_sql = "INSERT INTO tb_ipinfos (iplong1,iplong2,ipstr1,ipstr2,ipdesc) VALUES (?,?,?,?,?)";
charset = "gbk";
debug = true;
username = "root";
password = "****";
}
private void doStore() throws ClassNotFoundException, SQLException, IOException {
Class.forName("sql.jdbc.Driver");
Connection conn = Connection(connectStr, username,password);
conn.setAutoCommit(false); // 设置⼿动提交
PreparedStatement psts = conn.prepareStatement(insert_sql);
String line = null;
//开始执⾏时间
long begin = System.currentTimeMillis();
for(int i=0; i<500000; i++){
psts.setInt(1, i);
psts.setInt(2, i);
psts.setString(3, i + "ipstr1");
psts.setString(4, i + "ipstr2");
psts.setString(5, i + "ipstr3");
mysql下载add producepsts.addBatch(); // 加⼊批量处理
}
connmit(); // 提交
System.out.println("共⽤去时间" + (System.currentTimeMillis() - begin));
conn.close();
}
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException{
DbStoreHelper dbsh = new DbStoreHelper();
dbsh.doStore();
}
}
插⼊50万条数据只需要14秒,性能明显提⾼
在MySQL JDBC连接字符串中还可以加⼊参数,
useServerPrepStmts=false,如果不开启(useServerPrepStmts=false),使⽤sql.jdbc.PreparedStatement进⾏本地SQL拼装,最后送到db上就是已经替换了

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。