我通过jdbc向数据库插入几万条数据,要几十分钟,我是单条记录循环插入,请问有没有效率高一点的方法啊?

前提:还是要通过jdbc,其他我不考虑。

批处理 你插入一条 就连接一次数据库。。。。几万条 就连接几万次 理论和实际效率肯定会相对低一点呢 你可以吧你的数据装一个LIST里面 一次插入1000条 用毫秒数试试要多久 会不会好点 10000条又多久。。(当然 看你数据有多大的 不大就没问题) 然后循环插就好了 还有数据库表主键索引都建一下追问

你好,请问可否给点实例呢?

追答

失误。。。你是单纯得插入 不考虑数据源的查询 是我理解错了 插入只能一条一条插的 JDBC也没有hibernate那样还有什么优化配置之类的多。。。也只能在你数据库端优化了。索引 主键什么的都有点影响。。可以问问DBA 可以配置数据库不打印日志什么的等等。。。抱歉没能帮到你什么了。。。。

追问

没事,我再看看吧……

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-07-24

请搜索SQL.addBatch()方法,插入3万条,只需要几秒

public void fast_insert(PreparedStatement pst) {
try {

synchronized (pst) {
ct.setAutoCommit(false);
pst.executeBatch();
ct.commit();
}
定义一个PST。写在类里
PreparedStatement pst1 = null;
try {
pst1 = (PreparedStatement) sql.getConnection().prepareStatement(
"insert into cangku (c_number,c_list,c_phone,c_out) values(?,?,?,?)");
} catch (SQLException e1) {
e1.printStackTrace();
}
int ab = 1;

for (int h = 0; h < rows; h++) {
String number1 = rs.getCell(0, h).getContents().toString();

if (number1.length() < 2 || map.get(number1) != null) {
continue;
}

String list1 = rs.getCell(1, h).getContents().toString();
String phone1 = rs.getCell(2, h).getContents().toString();
String out1 = rs.getCell(5, h).getContents().toString();
try {
pst1.setString(1, number1);
pst1.setString(2, list1);
pst1.setString(3, phone1);
pst1.setString(4, out1);
pst1.addBatch();
} catch (SQLException e) {
e.printStackTrace();
}
p3_lab2.setText("插入了" + (ab++) + "条数据");
}
sql.fast_insert(pst1);//调用fast_insert方法,传入pst执行。
pst1 = null;
if(ab==1)
{
p3_lab2.setText("数据库资料已是最新!");
}
} catch (BiffException | IOException e1) {
e1.printStackTrace();
}