JDBC 插入无效

JDBC INSERT not working

我只是想在 table 中从 java 应用程序向 SQL 数据库插入一个新行。我以前使用过相同的代码并且它有效但由于某些原因它没有。我通过直接将查询插入 phpmyadmin 来检查我的查询并且它有效。这是我的代码:

我实际尝试发送查询的位置:

static Connection conn = MySQLAccess.connectDB();
static PreparedStatement pst = null;
static ResultSet rs = null;

public static String submit(String usrn, String psw){
    String sql = "INSERT INTO tbl_user VALUES('', '"+usrn+"', '"+psw+"')";

    try {
       pst = conn.prepareStatement(sql);
       System.out.println(sql);
       rs=pst.executeQuery();

       if (rs.next()){
           return "ok";
       } else {
           return "fail";
       }
    } catch (Exception e){
        return "fail_connection";
    }
}

MySQLAccess.java(我确信它有效,因为我在代码的其他地方使用了 is):

public class MySQLAccess {
    Connection conn=null;
    public static Connection connectDB (){
        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/g52gui","root","");
            return conn;
        }catch(Exception e){
            return null;
        }
    }
}

我刚刚更改了我的代码(Luiggi Mendoza 的建议)但没有结果:

public static String submit(String usrn, String psw){
        //String sql = "INSERT INTO tbl_user VALUES('', '"+usrn+"', '"+psw+"')";
        String sql = "INSERT INTO tbl_user VALUES('', '?', '?')";
        String result = "failed";
        try (Connection conn = MySQLAccess.connectDB();
             PreparedStatement pst = conn.prepareStatement(sql)) {
            pst.setString(1, usrn);
            pst.setString(2, psw);
            pst.executeUpdate();
            result = "worked";
        } catch (SQLException e) {
            //handle your exception...
        }
        return result;
    }

您应该使用 executeUpdate 而不是 executeQuery;

三期:

  1. 使用PreparedStatement#executeUpdate而不是PreparedStatement#executeQuery

  2. 将变量保持在尽可能窄的范围内。不要在 class.

  3. 中将它们设置为 static 变量
  4. 不要将参数连接到查询字符串中。相反,使用 PreparedStatement#setXyz 方法来设置正确的参数。

将所有这些粘合在一起产生以下代码:

public static String submit(String usrn, String psw){
    //String sql = "INSERT INTO tbl_user VALUES('', '"+usrn+"', '"+psw+"')";
    String sql = "INSERT INTO tbl_user VALUES('', ?, ?)";
    String result = "failed";
    try (Connection conn = MySQLAccess.connectDB();
         PreparedStatement pst = conn.prepareStatement(sql)) {
        pst.setString(1, usrn);
        pst.setString(2, psw);
        pst.executeUpdate();
        result = "worked";
    } catch (SQLException e) {
        //handle your exception...
    }
    return result;
}

从你的新代码来看,问题出在这里:

String sql = "INSERT INTO tbl_user VALUES('', '?', '?')";
                                              ^ ^  ^ ^

您用引号 ' 将参数字符 ? 括起来。删除此类引号,如我的代码所示:

String sql = "INSERT INTO tbl_user VALUES('', ?, ?)";
//No quotes around ?