【问题标题】:Unable to query database correctly using JDBC无法使用 JDBC 正确查询数据库
【发布时间】:2020-05-23 08:32:03
【问题描述】:

我正在尝试使用来自用户的输入更新数据库并将其保存在 jtable 中,然后使用 jtable 我正在更新数据库,但我无法获取并更新数据库中的第二行。

请提出解决方案,提前致谢。

        try {

            Class.forName("com.mysql.jdbc.Driver");
            con = myconnection.getConnection();

            String name;

            for (int i = 0; i < jTable2.getRowCount(); i++) {
                name = (String) jTable2.getModel().getValueAt(i, 0);
                String abcd = "select * from medicine where Name=? ";
                stmt = conn.prepareStatement(abcd);

                stmt.setString(1, name);
                rs = stmt.executeQuery();
                if (rs.next()) {

                    name = (String) jTable2.getModel().getValueAt(i, 0);
                    String stock = rs.getString("qty");
                    int nowstock = Integer.parseInt(stock);
                    int qty1 = Integer.parseInt(jTable2.getValueAt(i, 2).toString());

                    int newstock = nowstock - qty1;//Integer.parseInt(jTable2.getValueAt(i, 2).toString());
                    String sqlupdate = "UPDATE medicine SET qty='" + newstock + "'WHERE Name='" + name + "' ";  //
                    stmt = conn.prepareStatement(sqlupdate);
                    stmt.executeUpdate();

                }

            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Bill.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Bill.class.getName()).log(Level.SEVERE, null, ex);
        }

【问题讨论】:

  • 您能否在标题中提及您的问题陈述,例如 - 如何使用 Jtable 进行 CRUD?类似的东西 - 其他人寻找和提供解决方案会很有用。

标签: java database jdbc resultset


【解决方案1】:

选择没有任何作用,你可以迭代所有名称并直接更新:

for (int i=0; i < jTable2.getRowCount(); i++) {
    String name = (String) jTable2.getModel().getValueAt(i, 0);
    int qty1 = Integer.parseInt(jTable2.getValueAt(i, 2).toString());
    String update = "UPDATE medicine SET qty = qty - ? WHERE Name = ?";
    PreparedStatement ps = conn.prepareStatement(update);
    ps.setInt(1, qty1);
    ps.setString(2, name);
    ps.executeUpdate();
}

如果您的 JTable 碰巧有超过 10 个左右的名称,那么更有效的方法是使用带有 WHERE IN 子句的单个更新,其中包含出现在表中的所有名称,即

UPDATE medicine SET qty = qty - ? WHERE Name IN (...);

【讨论】:

  • 您的药表中没有“第二”行。如果更新未能更新您期望的某些行,那么您应该首先检查名称是否匹配。
猜你喜欢
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2012-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多