【问题标题】:Execute Multiple JDBC Queries In a Defined Sequence以定义的顺序执行多个 JDBC 查询
【发布时间】:2015-09-18 16:46:49
【问题描述】:

我正在开发一个通过 JDBC 连接 MySQL 的应用程序。在一个动作中,我需要执行两个查询,sql to read,sql to update。

为了确保首先执行读取查询的 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();
            }
        }

【问题讨论】:

  • 如果你展示你迄今为止尝试过的东西,你将更有可能有人回答。

标签: mysql sql jdbc transactions


【解决方案1】:

在调用preparedStatementUpdate.executeUpdate()之前尝试执行rs.next() while循环;

【讨论】:

  • 试过你的建议,还是mysql先执行'UPDATE',然后'SELECT'。这不是我想要的。
猜你喜欢
  • 2011-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多