【问题标题】:Java Mysql Update StatementJava Mysql 更新语句
【发布时间】:2011-10-18 08:57:28
【问题描述】:

我正在尝试使用 Java Swing 更新 mysql 记录。似乎 MySql Update 语句有问题。我已将代码粘贴如下:

conDBase = getConnection();
stmt = conDBase.createStatement();

String sql = "update user set role = " + jComboBox1.getSelectedItem()+  "where userID =" +  jComboBox2.getSelectedItem();

stmt.executeUpdate(sql);
conDBase.close();
JOptionPane.showMessageDialog(null, "User Role Updated");
this.dispose();
new Admin().setVisible(true);

【问题讨论】:

  • 您面临的问题是什么?
  • 您无法使用 Java Swing 更新 MySQL 行。

标签: java mysql swing


【解决方案1】:

嗯,你的代码至少有两个问题:

  • 您没有使用准备好的语句,这意味着您已经为 SQL 注入敞开了大门。 (您甚至没有引用您正在使用的值,这可能算作第三个问题。)
  • “where”子句之前没有空格

我怀疑这是您现在注意到的后一个问题,但您应该绝对修复代码以使用准备好的语句。

哦,您可能也不应该在 UI 线程上执行任何这些操作(或从非 UI 线程访问 UI 控件)...

【讨论】:

    【解决方案2】:

    我不确定您收到什么错误消息(也许您可以发布一些详细信息)。

    但是,需要更改以下行:

    String sql = "update user set role = " + jComboBox1.getSelectedItem()+  " where userID =" +  jComboBox2.getSelectedItem() + ";";
    

    注意“where”之前的空格和语句末尾的分号。

    更好的版本应该是这样的:

    public int updateRoleForUser (String role, Integer userId) throws Exception {
    
    int i = 0;
    
    String sql =
                " update user "
                + " set role = ?"
                + " where userId = ?;";
    
        try {
            conDBase = getConnection();
            ps = conDBase.prepareStatement(sql);
            ps.setString(1, role);
            ps.setInt(2, userId);
    
            i = ps.executeUpdate();
        } catch (Exception e) {
            // do something with Exception here. Maybe just throw it up again
        } finally {
            closeConnection();
            return i;
        }
    };
    

    然后使用组合框中的值调用该方法。

    你真的应该把所有的东西都放在某个描述的 DAO 类中的一个方法中,然后将角色和 userId 值作为参数传递;

    【讨论】:

      【解决方案3】:

      您必须在引号和“where”之间放置一个空格。像这样:

      ...getSelectedItem() + " where...
      

      因为如果没有,你会得到类似的东西:

      ...set role = 25where userId...
      

      【讨论】:

        猜你喜欢
        • 2010-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-03
        • 2012-08-29
        • 2016-09-03
        • 2017-09-05
        • 1970-01-01
        相关资源
        最近更新 更多