java代码中的语法不适用于mysql。来自Java的setString()
将带有'而不是`,这在MySQL中是不被接受的。
我尝试在本地主机上运行代码,它实际上不接受'doctor',而仅接受'doctor`。
下面是我的代码:
PreparedStatement ps = con.prepareStatement("SELECT id FROM ? WHERE id = ?");
ps.setString(1, "doctor");
ps.setInt(2, 123);
ResultSet rs = ps.executeQuery();
有错误
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 ''doctor' WHERE id = 123' at line 1
答案 0 :(得分:2)
这是因为您的代码会产生以下查询:
SELECT id FROM 'doctor' WHERE id = 123
如您所见,表名被用作无效SQL语法的字符串,因此您可以硬编码table name
,或者如果您真的希望它是动态的,则可以像这样实现它:
String sql = String.format("SELECT id from %s where id = ?", tblName);
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 123);
ResultSet rs = ps.executeQuery();