PreparedStatement throws syntax error [duplicate]

2020-02-02 03:19发布

Im preparing a query using PreparedStatements and it runs fine when i hardcode te query with the condition parameter.

but throws error , if the parameter is passed from setString() method.

com.mysql.jdbc.JDBC4PreparedStatement@2cf63e26: select * from linkedin_page_mess ages where company_id = '2414183' com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '?' at line 1

In the error log, above my query looks fine.

public JSONObject getLinkedInMessages(String compId)
    {
            linlogger.log(Level.INFO, "Called getLinkedInMessages method");
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        JSONObject resObj = new JSONObject();
        JSONArray tempArray = new JSONArray();
        try
        {
            conn = InitOrGetConnection();
            String query = "select * from linkedin_page_messages where company_id = ?";
            PreparedStatement pst=conn.prepareStatement(query);
            pst.setString(1, compId);
            System.out.println("\n\n"+pst.toString());
            rs= pst.executeQuery(query);


             // process resultset logics
        }
       catch(Exception e)
        {   
            System.out.println(e);
            linlogger.log(Level.INFO, "Exception occured "+e.toString());
        }
    }

Is there anything wrong with the PreparedStatements?

2条回答
男人必须洒脱
2楼-- · 2020-02-02 04:10

remove the parameter in this line:

rs= pst.executeQuery(query);

It must be

rs= pst.executeQuery();

Because the statement is prepared at PreparedStatement pst=conn.prepareStatement(query);

execute(String sql) is inherited from Statement and will execute the satement (sql) without prepared it.

查看更多
再贱就再见
3楼-- · 2020-02-02 04:17

Remove the parameter from

rs= pst.executeQuery(query);

change to

rs= pst.executeQuery();

If you pass query in pst.executeQuery(query); as parameter then this passed query string take priority over the query string you passed in conn.prepareStatement(query); and since in query(select * from linkedin_page_messages where company_id = ?) you dint pass parameter you get the error.

查看更多
登录 后发表回答