JDBC使用占位符插入数据报错:
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?,?)' at line 1
String sql = "INSERT INTO `sys_user` (`sys_name`, `sys_pwd`) VALUES (?,?)";
int num = 0;
try {
pstmt = conn.prepareStatement(sql);
// 使用占位符
pstmt.setString(1, userName);
pstmt.setString(2, password);
num = pstmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return num;
pstmt = conn.prepareStatement(sql);
这个已经将sql语句设置了
pstmt.setString(1, userName);
pstmt.setString(2, password);
** num = pstmt.executeUpdate(sql);**
executeUpdate();方法是没有参数的
但是pstmt.executeUpdate(sql);这样写编译器是不会报错的
所以 这里就不要在executeUpdate()加入sql参数,不然认会为是按照sql中有值的方式不是占位符的形式来执行
将 num = pstmt.executeUpdate()(sql);
改为
num = pstmt.executeUpdate();
后运行能够成功插入sql语句