Java derby数据库无法正常工作

时间:2017-08-03 09:00:39

标签: java mysql sql jdbc

这些代码行有什么问题吗?我得到的只是“无效录入”。 我有一个名为production的数据库,其中有一个名为PRODUCTION的表。

try {
    String mk = jTextField1.getText();
    String mn = jTextField2.getText();
    String ab = (String) jComboBox1.getSelectedItem();
    String bc = (String) jComboBox2.getSelectedItem();

    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:1527/production");
        {
            String host = "jdbc:mysql://localhost:1527/production";
            JOptionPane.showMessageDialog(this, "connection success");
            Statement stmt = con.createStatement();

            String query = "update PRODUCT set FACTORY='" + ab + "' PRODUCT_NAME = '" + mk + "' UNIT= '" + bc + "' and OPENING_BALANCE'" + mn + "');";
            stmt.executeUpdate(query);
            JOptionPane.showMessageDialog(this, "Record has been inserted");
            stmt.close();
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "invalid entry");
    }
} catch (Exception e) {
    JOptionPane.showMessageDialog(null, "Error in Connectivity", "Message", 2);
}

1 个答案:

答案 0 :(得分:1)

您的查询不正确:

  1. 您必须在字段
  2. 之间使用,
  3. 您不需要使用和设置字段(and OPENING_BALANCE'" + mn + "'
  4. 在您的查询结尾处有一个您不需要它的封闭括号)
  5. 但你的方式是对sytax错误和SQL Inection开放,你必须使用PreparedStatement,它更安全,更有帮助:

    query = "update PRODUCT set FACTORY = ?, PRODUCT_NAME = ?, UNIT= ?, OPENING_BALANCE = ?";
    try (PreparedStatement update = connection.prepareStatement(query)) {
    
        update.setString(1, ab);
        update.setString(2, mk);
        update.setString(3, bc);
        update.setString(4, mn);
    
        update.executeUpdate();
    }