我已编写以下代码(摘录):
conn = Pooling.getDataSource().getConnection();
String databaseName = Configuration.getDatabaseName();
String sql = "SELECT * FROM " + databaseName + ".companies WHERE companyemail = ? AND companypassword = MD5(?)";
PreparedStatement prepStat = conn.prepareStatement(sql);
prepStat.setString(1, username);
prepStat.setString(2, password);
System.out.println("LoginService: prepStat = " + prepStat.toString());
ResultSet rs = prepStat.executeQuery(sql);
...
现在,当我执行此操作时,我获得了MySQLSyntaxErrorException
。 prepStat.toString()
打印:
SELECT * FROM dbname.companies WHERE companyemail = 'comp@comp.com' AND companypassword = MD5('passwort')
对SequelPro的简单复制和粘贴成功返回结果。
但是,后端仍然声称语法中存在错误:
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 '? AND companypassword = MD5(?)' at line 1
也许我是盲人,但我没有看到错误?但是这里发生了什么?
答案 0 :(得分:1)
好的,我发现了问题所在。我用过:
ResultSet rs = prepStat.executeQuery(sql);
但是,我应该使用
ResultSet rs = prepStat.executeQuery();
代替。
答案 1 :(得分:0)
试试这个:
String sql = "SELECT * FROM '" + databaseName + ".companies' WHERE companyemail=? AND companypassword = MD5(?)";
注意databaseName变量之前和.companies之后的单引号。我认为这可能是问题所在。
或者你可以这样做:
String sql = "SELECT * FROM ? WHERE companyemail =? AND companypassword = MD5(?)";
PreparedStatement prepStat = conn.prepareStatement(sql);
prepStat.setString(1, databaseName);
prepStat.setString(2, username);
prepStat.setString(3, password);
我认为问题在于将databaseName解析为准备好的语句。