我尝试使用JDBC使用PreparedStatement通过以下方法插入userId(int)和userName(String):
public boolean saveUser(int userId, String userName){ boolean saveStatus = false; try { connection.setAutoCommit(true); String sql = "insert into testtable values(?,?)"; PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(1, userId); statement.setString(2, userName); saveStatus = statement.execute(sql); } catch (SQLException e) { e.printStackTrace(); }finally{ Connector.closeConnections(); } return saveStatus; }
我得到以下堆栈跟踪:
com.mysql.jdbc.exceptions.jdbc4.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
我究竟做错了什么?
试试这个,这应该工作:
try { connection.setAutoCommit(true); String sql = "insert into testtable values(?,?)"; PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(1, userId); statement.setString(2, userName); saveStatus = statement.execute(); } catch (SQLException e) { e.printStackTrace(); } return saveStatus; }
PreparedStatement是预编译的语句。您不必在执行时提供sql字符串。