您的位置:首页 > 数据库 > MySQL

MySql海量数据批量插入优化小结

2016-02-18 15:35 621 查看
以前学习的时候玩mysql无非弄几万条数据意思一下就行了,今天无聊写了一个程序,需要插入2000W以上的数据,这数据量一大就出现问题了

问题1:使用普通的单条插入效率非常低;

解决方法:使用PreparedStatement的addBatch()方法来批量插入

(String url = "jdbc:mysql://127.0.0.1/double?useServerPrepStmts=false&rewriteBatchedStatements=true";)这样设置可以优化效率

DBHelper db = new DBHelper();
sql ="insert into coculatenumber_2000w_index SET r1=?, r2=?,r3=?,r4=?,r5=?,r6=?,b1=?,date=?,info=?";

try {
db.conn.setAutoCommit(false);//1,先关闭自动提交

db.pst=db.conn.prepareStatement(sql);//2,预编写sql语句

} catch (SQLException e1) {
e1.printStackTrace();
}
while (i<end) {
try
{
db.pst.setInt(1, test.get(0));//3,改写参数
db.pst.setInt(2, test.get(1));
db.pst.setInt(3, test.get(2));
db.pst.setInt(4, test.get(3));
db.pst.setInt(5, test.get(4));
db.pst.setInt(6, test.get(5));
db.pst.setInt(7, test.get(6));
db.pst.setString(8, df.format(new Date()));
db.pst.setString(9, info);
db.pst.addBatch();//4,批量处理关键代码
} catch (SQLException e) {
e.printStackTrace();
}
}
try {

db.pst.executeBatch();//4,执行批量处理

db.conn.commit();
db.conn.close();

} catch (SQLException e) {
e.printStackTrace();
}


问题2:4G内存的电脑,一次插入23W左右的数据时,内存溢出报错;

解决方法:分批进行操作,每10W左右进行一次提交

<span style="white-space:pre">	</span>int part=100000;//每次10W
int all=20000000;//一共2000W
int times=all/part;
if (all%part!=0) {
times++;
}
long starttime=(new Date()).getTime();
for (int i = 0; i < times; i++) {
if (i*part<all&&i==times-1) {
doByPart(i,times,i*part,all,all,"x006");
}else {
doByPart(i,times,i*part,(i+1)*part,all,"x006");
}
}
long endtime=(new Date()).getTime();
long ltimes=(endtime-starttime)/1000;
System.out.println("操作完成!耗时:"+ltimes+"秒.");


问题3:对数据进行查询时速度慢

解决方法:对mysql的表进行优化,插入索引,可以使用EXPLAIN 来看索引是否用上了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql 海量数据 优化