如果您从笔记本电脑上运行JDBC程序,该程序通过Wi-Fi连接到办公室网络。 如果在循环(JDBC)结果集时网络丢失会发生什么? 我注意到java.sql.Connection& Statement对象有超时。但结果集没有超时设置。
ResultSet rs = st.getResultSet();
while (rs.next()) {
int id = rs.getInt(1);
// use this and run some biz logic.
}
我注意到程序一直在等待下一个结果。怎么让它抛出异常?有没有人经历过这个?你做了什么?
答案 0 :(得分:0)
ResultSet将不再可用,但您可以做的是:
您有两种选择:
首先:(我建议)使用交易,正如Oracle doc所说:
创建连接时,它处于自动提交模式。这意味着 将每个单独的SQL语句视为事务并且是 执行后立即自动提交。 (更多 精确,默认情况下是SQL语句提交时 完成,而不是在执行时。所有声明都完成了 已检索到其结果集和更新计数。几乎 但是,所有情况下,声明都已完成,因此已经提交, 它被执行后立即。)
在您的情况下,您应该在完成所有语句后执行一次,如果网络出现故障或在一个语句中出现任何错误,您的所有语句都将回滚
示例: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);
}
}
第二:您可能必须在连接丢失之前缓冲所有结果,但要注意关闭结果集,语句和连接