问题
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