【问题标题】:Unable to update database in MySQL, Java无法在 MySQL、Java 中更新数据库
【发布时间】:2021-10-09 00:05:04
【问题描述】:

我是 SQL 和数据库的新手。请用基本语言回答我的问题。 我无法更新仅包含一个表和一列的数据库值。它由我需要选择用户角色的角色值(INT 类型)组成。代码如下:

else if (check==13)//failing to update
{
    try
    {
        Connection connection = DriverManager.getConnection(url, username, password);
        Statement s=connection.createStatement();
        ResultSet pass=s.executeQuery("Select * from role");
        PreparedStatement ps;
        int up=cval;// cval is a int value from outside the else if block
        if ((up<0)||(up>3))
            System.out.println("Role doesn't exist");
        else {
            ps = connection.prepareStatement("Update role set roleid="+up);
            ps.executeUpdate();
        }
        while (pass.next())
            role=pass.getInt("roleid");
        if (role==up)
            System.out.println("Role changed successfully\n");
        else
            System.out.println("Role change unsuccessful\n");
    }
    catch (Exception e)
    {
        System.out.println("Connection failed");
    }
}

每次我检查值时它都不会更新。但是,如果我再次执行此代码块,它会更新。连接没有问题,因为我也对我的数据库做了其他事情。

【问题讨论】:

    标签: java mysql sql jdbc sql-update


    【解决方案1】:

    您在更新表之前获得了 ResultSet pass,因此它包含旧值。

    移动这一行:

    ResultSet pass=s.executeQuery("Select * from role");
    

    更新表格后。

    【讨论】:

    • 非常感谢我的代码现在可以正常工作非常感谢❤️❤️❤️
    • @Cap 很好,如果它有效并且不要忘记在 5 分钟左右后点击复选标记来接受答案。
    【解决方案2】:
    ps=connection.prepareStatement("Update role set roleid=?");
    ps.setInt(1,up);
    ps.executeUpdate();
    

    prepareStatement 代码错误

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 2015-07-23
      • 2014-11-10
      • 2013-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多