有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

mysql Java更新查询并非每次都有效

这个查询在开始时有效,但当我一次又一次地更新它时,它停止了工作。我正在使用netbeans和xampp服务器
还有一件奇怪的事,现在当值被更新时,最后两行和最后一列保持不变

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

    String val = txt_val.getText();
    String col = txt_col.getText();
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost/net", "root", "");

        pstmt = conn.prepareStatement(
        "update userdetail set 
            name =  ?
        , username =  ? where  name =  ? AND  username =  ? ")

        pstmt.setString(1, val);
        pstmt.setString(2, val);

        pstmt.setString(3, col);
        pstmt.setString(4, col);

        int i = pstmt.executeUpdate();
        if (i > 0) {
            JOptionPane.showMessageDialog(null, "done");
        } else {
            JOptionPane.showMessageDialog(null, "query failed");
        }

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }

}

共 (1) 个答案

  1. # 1 楼答案

    This query worked at the start but when I updated it again and again it stopped working

    这是逻辑,问题在于你的查询:

    问题

    update userdetail set name = ?, username = ? where name = ? AND username = ?
    

    假设你的name = "name" and username = "username在数据库中
    新值name = "name1" and username = "username1"

    第一次更新

    .. set name = "name1", username = "username1" where name = "name" AND username = "username"
    

    第二次更新

    如果您再次重复,您将使用旧的名称和用户名值重复查询:

    .. set name = "name2", username = "username2" where name = "name" AND username = "username"
    

    名称和用户名是第一次更改的,在数据库中没有这样的值:name = "name" AND username = "username"


    解决方案

    在更新之前,您必须从数据库中获取信息,以便可以毫无问题地更新记录

    最佳做法是使用不会更改的主键更新记录,例如:

    update ... where id = something
    

    希望你明白我的意思