问题
I have written a prepared statement but its giving a syntax error at ?. I am not able to understand whats wrong.It should pass a movie name and get the result as directors of that movie
stmt=getConnection().createStatement();
String sql="SELECT directors FROM moviedata WHERE moviedata.title = ?";
PreparedStatement preparedStatement=conn.prepareStatement(sql);
preparedStatement.setString(1,movieName);
rs=preparedStatement.executeQuery(sql);
回答1:
The problem is here:
rs=preparedStatement.executeQuery(sql);
You shouldn't pass the SQL String to executeQuery(), since the prepared statement already contains the SQL String with the ? placeholder replaced by the value of movieName.
Use:
rs=preparedStatement.executeQuery();
回答2:
The problem is not in using Preparedstatement >Because the prepared statement object holds the sql query. The why again unnecessarily passing Sql string to executequery() method.PreparedStatement preparedstatement=conn.PrepareStatement(sql). This holds the sql query and when executequery() method is called The query is evaluated.
来源:https://stackoverflow.com/questions/43833033/why-do-i-get-a-syntax-error-for-prepared-statement