我正在开发一个通过JDBC连接MySQL的应用程序。在一个动作中,我需要执行两个查询,sql读取和sql更新。
为了确保,首先执行sql读取查询,然后执行sql更新以便执行,我使用JDBC事务。但不知何故,问题是,mysql首先执行第二个查询,然后是第一个读取查询。
寻找建议。非常感谢。
// Sql connection
Connection conn = null;
Statement stmt = null;
PreparedStatement preparedStatement = null;
PreparedStatement preparedStatementUpdate = null;
String sql = "SELECT item_name, item_detail FROM Order_Printing where kitchen_id = ? and order_printed = ?";
String sqlFlag = "UPDATE order_printing set order_printed = 1 where kitchen_id = ?";
try {
// Register JDBC driver (Note to add mysql connector jar file)
Class.forName("com.mysql.jdbc.Driver");
// Step 3: open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
conn.setAutoCommit(false); // Disable auto-commit mode
preparedStatement = conn.prepareStatement(sql);
preparedStatement.setInt(1, 4);
preparedStatement.setInt(2, 0);
ResultSet rs = preparedStatement.executeQuery();
//
preparedStatementUpdate = conn.prepareStatement(sqlFlag);
preparedStatementUpdate.setInt(1, 4);
preparedStatementUpdate.executeUpdate();
int startingPos = 10;
int orderNumber = 1;
while (rs.next()) {
String item_name = "Order " + orderNumber++ + ": ";
item_name += rs.getString("item_name");
String item_detail = rs.getString("item_detail");
startingPos += 20;
g.drawString(item_name, 0, startingPos);
startingPos += 20;
g.drawString(item_detail, 0, startingPos);
}
conn.commit();
} catch (SQLException se) {
se.printStackTrace();
} catch (ClassNotFoundException se) {
se.printStackTrace();
} catch (Exception se) {
se.printStackTrace();
} finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
答案 0 :(得分:0)
在调用preparedStatementUpdate.executeUpdate();
之前尝试执行rs.next()while while循环