简单的用JDBC连接数据库,采用的是PreparedStatement进行数据查询,
连接数据库的时候出现这种问题:
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 = "select * from charge where user_id = ?";
Connection connection = ConnUtil.getConnection();
PreparedStatement statement = null;
ResultSet resultSet = null;
List<Charge> charges = null;
try {
statement = connection.prepareStatement(sql);
statement.setInt(1, userId);
resultSet = statement.executeQuery(sql);
一开始以为是SQL写的有问题,然后尝试将“?”替换成数字,发现是可以的
select * from charge where user_id = 1
所以就很无语了。在网上查了好久,最后发现将下面语句替换下就可以了:
resultSet = statement.executeQuery(sql);
替换成:
resultSet = statement.executeQuery();
具体为什么还来不及去研究
参考:http://stackoverflow.com/questions/7574134/jdbc-returning-mysqlsyntaxerror-exception-with-correct-statement