我只是尝试将表中的新行从 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(我确信它可以工作,因为我在代码的其他地方使用过):
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;
}
最佳答案
三个问题:
使用
PreparedStatement#executeUpdate
而不是PreparedStatement#executeQuery
。将变量保持在尽可能小的范围内。不要将它们设置为类中的
静态
变量。不要将参数连接到查询字符串中。相反,请使用
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 ?
关于java - JDBC 插入不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29752642/