用JDBC 批处理插入数据出错后不能回滚,数据库是mysql 插入的数据是60000条数据。mysql里还是保存了部分的数据。请知道原因的朋友麻烦解决哈谢谢
try{
fr = new FileReader(file);
br = new BufferedReader(fr,6*1024);
con = this.getSession().connection();
con.setAutoCommit(false);
ps = con.prepareStatement("insert into test value(?,?,?,?,?,?,?,?)");
// System.out.println(con.getAutoCommit());
while ((line=br.readLine())!=null) {
fields = line.split(",");
ps.setString(1, fields[0]);
ps.setInt(2, fields[1]);
ps.setInt(3, 0);
ps.setInt(4, 0);
ps.setInt(5, 0);
ps.setInt(6, 0);
ps.setInt(7, 0);
ps.setInt(8, 0);
ps.addBatch(); i++;
if(i%5000==0){
ps.executeBatch(); }
}
ps.executeBatch();
con.commit();
}catch(Exception e){
try {
con.rollback();
} catch (Exception e1) {
}}
try{
fr = new FileReader(file);
br = new BufferedReader(fr,6*1024);
con = this.getSession().connection();
con.setAutoCommit(false);
ps = con.prepareStatement("insert into test value(?,?,?,?,?,?,?,?)");
// System.out.println(con.getAutoCommit());
while ((line=br.readLine())!=null) {
fields = line.split(",");
ps.setString(1, fields[0]);
ps.setInt(2, fields[1]);
ps.setInt(3, 0);
ps.setInt(4, 0);
ps.setInt(5, 0);
ps.setInt(6, 0);
ps.setInt(7, 0);
ps.setInt(8, 0);
ps.addBatch(); i++;
if(i%5000==0){
ps.executeBatch(); }
}
ps.executeBatch();
con.commit();
}catch(Exception e){
try {
con.rollback();
} catch (Exception e1) {
}}
If one of the commands in a batch update fails to execute properly, this method throws a BatchUpdateException, and a JDBC driver may or may not continue to process the remaining commands in the batch.关键就在这个“may or may not ”
也就是说jdbc驱动可以继续也可以不继续做接下来的命令。可能oracle的驱动是"may"
而楼主现在的数据库的jdbc驱动是“may not”楼主参考参考吧btw:javadoc说“throws a BatchUpdateException”,但是根据楼主的描述,也没抛出这个exception到楼主程序的catch里面,
难道说被executeBatch方法给“吃掉了”??明白人来给说道说道吧good luck
既然换成Oracle没有问题,肯定就是数据库设置的问题了。
我看到标题第一时间想到的就是这个
try{
fr = new FileReader(file);
br = new BufferedReader(fr,6*1024);
con = this.getSession().connection();
con.setAutoCommit(false);
Transaction trans = db.createTransaction(conn);
trans.begin();
//构选 insert语句...
...
i++;
if(i%5000==0){
trans.executeSQL();
}
}
trans.executeSQL(); trans.commit();
}
catch(Exception e){
try {
trans.rollback();
}
catch (Exception e1) {
}
}
finally{
trans.close();
con.close;
}