1. 程式人生 > >JDBC使用佔位符插入資料報錯MySQLSyntaxErrorException: You have an error.....syntax to use near '?,?)'

JDBC使用佔位符插入資料報錯MySQLSyntaxErrorException: You have an error.....syntax to use near '?,?)'

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語句