gpt4 book ai didi

java - 在循环 JDBC 结果集时,如果我们失去网络会发生什么?

转载 作者:太空宇宙 更新时间:2023-11-04 11:23:08 25 4
gpt4 key购买 nike

如果您从通过 wi-fi 连接到办公室网络的笔记本电脑运行 JDBC 程序。如果在循环 ( JDBC ) 结果集时网络丢失会发生什么?我注意到 java.sql.Connection 和 Statement 对象超时。但结果集没有超时设置。

ResultSet rs = st.getResultSet();
while (rs.next()) {
int id = rs.getInt(1);
// use this and run some biz logic.
}

我注意到程序一直在等待下一个结果。如何让它抛出异常?有人经历过吗?你做了什么?

最佳答案

ResultSet 将不再可用,但您可以做的是:

您有两个选择:

首先:(我建议)使用交易,如 Oracle doc说:

When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and is automatically committed right after it is executed. (To be more precise, the default is for a SQL statement to be committed when it is completed, not when it is executed. A statement is completed when all of its result sets and update counts have been retrieved. In almost all cases, however, a statement is completed, and therefore committed, right after it is executed.)

在您的情况下,您应该在所有语句完成后执行一次,如果网络故障或一条语句中出现任何错误,您的所有语句都将回滚

示例:reference

public void updateCoffeeSales(HashMap<String, Integer> salesForWeek)
throws SQLException {
PreparedStatement updateSales = null;
PreparedStatement updateTotal = null;
String updateString =
"update " + dbName + ".COFFEES " +
"set SALES = ? where COF_NAME = ?";
String updateStatement =
"update " + dbName + ".COFFEES " +
"set TOTAL = TOTAL + ? " +
"where COF_NAME = ?";
try {
con.setAutoCommit(false);
updateSales = con.prepareStatement(updateString);
updateTotal = con.prepareStatement(updateStatement);
for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
updateSales.setInt(1, e.getValue().intValue());
updateSales.setString(2, e.getKey());
updateSales.executeUpdate();
updateTotal.setInt(1, e.getValue().intValue());
updateTotal.setString(2, e.getKey());
updateTotal.executeUpdate();
con.commit();
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
if (con != null) {
try {
System.err.print("Transaction is being rolled back");
con.rollback();
} catch(SQLException excep) {
JDBCTutorialUtilities.printSQLException(excep);
}
}
} finally {
if (updateSales != null) {
updateSales.close();
}
if (updateTotal != null) {
updateTotal.close();
}
con.setAutoCommit(true);
}
}

第二:您可能必须在连接丢失之前缓冲所有结果,但要注意关闭结果集、语句和连接

关于java - 在循环 JDBC 结果集时,如果我们失去网络会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44690773/

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