why do I get a syntax error for prepared statement? [duplicate]

早过忘川 提交于 2019-12-02 01:35:58

问题


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

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