gpt4 book ai didi

Java : Insert query-Exception

转载 作者:行者123 更新时间:2023-11-29 06:19:30 24 4
gpt4 key购买 nike

我对数据库操作有疑问。我有一个应该运行 10 次的插入查询。循环开始并在插入第 6 个时插入 4 或 5 个值,数据库连接暂时失败并再次连接。那么会发生什么,它是跳过那个特定的 val 还是抛出异常或回滚整个操作?

编辑:示例代码

try
{
String sql_ji_inser="insert into job_input values (?,?)";
PreparedStatement pst_ji_inser=OPConnect.prepareStatement(sql_ji_inser);

for(int i=0;i<v_new_data.size();i++)
{
Vector row=new Vector();
row=(Vector)v_new_data.get(i);

job_id=Integer.parseInt(row.get(0).toString());
item_no=Integer.parseInt(row.get(1).toString());
pst_ji_inser.setInt(1,job_id);
pst_ji_inser.setInt(2,item_no);
pst_ji_inser.addBatch();
}
System.out.println("No of rows inserted"+pst_ji_inser.executeBatch().length);
}
catch(Exception ex)
{
System.out.println("********Insert Exception*********************");
ex.printStackTrace();
return false;
}

这样对吗

try 
{
int count=0;// for checking no of inserting values
OPConnect.setAutoCommit(false);
String sql_ji_inser="insert into job_input values (?,?)";
PreparedStatement pst_ji_inser=OPConnect.prepareStatement(sql_ji_inser);
for(int i=0;i<v_new_data.size();i++)
{
job_id=Integer.parseInt(row.get(0).toString());
item_no=Integer.parseInt(row.get(1).toString());
pst_ji_inser.setInt(1,job_id);
pst_ji_inser.setInt(2,item_no);
pst_ji_inser.addBatch();
count++;
}
int norowinserted=pst_ji_inser.executeBatch().length;
if(count==norowinserted)
{
OPConnect.commit();
}
}
catch(Exception ex)
{
System.out.println("********Insert Exception*********************");
OPConnect.rollback();
ex.printStackTrace();
return false;
}

最佳答案

这取决于您插入行的方式。如果您将它们插入到一个连接上的单个事务中,该连接已被 connection.setAutoCommit(false) 关闭了自动提交,并且您在使用 完成插入查询后提交了连接connection.commit() 并且您在 catch block 内显式调用 connection.rollback(),然后整个事务将被回滚。否则,您将依赖于您无法控制的环境因素。

另见:


更新:这是对您的代码的重写。注意连接和语句要在try之前声明,在try获取,在finally关闭。这是为了防止出现异常时发生资源泄漏。

String sql = "insert into job_input values (?, ?)";
Connection connection = null;
PreparedStatement statement = null;

try {
connection = database.getConnection();
connection.setAutoCommit(false);
statement = connection.prepareStatement(sql);

for (List row : data) {
statement.setInt(1, Integer.parseInt(row.get(0).toString()));
statement.setInt(2, Integer.parseInt(row.get(1).toString()));
statement.addBatch();
}

statement.executeBatch();
connection.commit();
return true;
} catch (SQLException e) {
if (connection != null) try { connection.rollback(); } catch (SQLException logOrIgnore) {}
e.printStackTrace();
return false;
} finally {
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}

顺便说一句,我不喜欢在这里返回一个boolean。我只是让方法 void,让 catch throw e 并将调用代码放在 try-catch.

关于Java : Insert query-Exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3740360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com