Why am i getting a syntax error with this prepared statement?

纵饮孤独 提交于 2019-12-24 10:58:51

问题


I am trying to learn how to do a PreparedStatement as follows:

createConnection();
conn.setAutoCommit(false);
String sql = "SELECT MAX(?) FROM ?";
PreparedStatement stmt = conn.prepareStatement(sql);

However, when I hit the last line, it throws a java.sql.SQLSyntaxErrorException as follows:

java.sql.SQLSyntaxErrorException: Syntax error: Encountered "?" at line 1, column 20.

I have searched everywhere but cant find any reason for it to fail. What am I doing wrong? later on in the code I am setting the ? parameters as meaning full string values but when I debug I never get to that point. It hits this conn.prepareStatement line and throws the exception. Thanks for the help. I don't know if it makes a difference but it is on a derby database.


回答1:


Think of your ? mark as a sql variable. You can't do a select MAX on a variable, it's syntactically incorrect.

You can't do the following:

declare @myvar int
select @myvar = 1

SELECT MAX(@myvar) from SomeTable


来源:https://stackoverflow.com/questions/10739408/why-am-i-getting-a-syntax-error-with-this-prepared-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!