public int addTypes(List<taobaoBean> babyList) {
String sql = "insert into type (typeid,url) values (?,?) ";
Connection conn = dbhelper.getConnection(driver,url,username,upwd);
int result = 0;
PreparedStatement stmt =null;
try {
stmt = conn.prepareStatement(sql);
for(int i=0;i<babyList.size();i++){
stmt.setInt(1, babyList.get(i).getTypeId());
stmt.setString(2, babyList.get(i).getUrl());
stmt.addBatch();
}
stmt.executeBatch();
} catch (Exception e) {
e.printStackTrace();
}finally{
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
dbhelper.closeCon(conn);
}
return result;
}
1分钟才插入3000条数据,如何变快。
批处理,,成批的插入
批量插入,不要一条条插入,mysql支持一次插入多条记录
有两种方法:
1. 一条SQL语句插入多条数据。
INSERT INTO insert_table
(datetime
, uid
, content
, type
) VALUES ('0', 'userid_0', 'content_0', 0);
INSERT INTO insert_table
(datetime
, uid
, content
, type
) VALUES ('1', 'userid_1', 'content_1', 1);
可以将上面这种一条条插入的语句合并成下面这种
INSERT INTO insert_table
(datetime
, uid
, content
, type
) VALUES('0', 'userid_0', 'content_0', 0), ('1', 'userid_1', 'content_1', 1);
这种方法可以减少SQL语句解析的操作, 只需要解析一次就能进行数据的插入操作,而且SQL语句较短,可以减少网络传输的IO。
2.在事务中进行插入处理
START TRANSACTION;
INSERT INTO insert_table
(datetime
, uid
, content
, type
) VALUES ('0', 'userid_0', 'content_0', 0);
INSERT INTO insert_table
(datetime
, uid
, content
, type
) VALUES ('1', 'userid_1', 'content_1', 1);
...
COMMIT;
通过使用事务可以减少数据库执行插入语句时多次“创建事务,提交事务”的消耗,所有插入都在执行后才进行提交操作。
注:两种方法我测了下插入1W条的话,第一种方法和第二种方法之前都要大概11秒,优化以后第一种只要0.2秒,第二种要1秒
LZ也可以两种结合在一起用
inert into targetTable (id,name)
select id,name from otherTable
我现在这样做的,100万数据,测试环境下40秒左右,根据你的服务器进行优化吧。