PreparedStatement抛出语法错误

时间:2015-04-28 06:58:26

标签: java mysql jdbc prepared-statement

我正在使用PreparedStatements准备一个查询,当我用条件参数硬编码查询时它运行正常。

但如果参数是从setString()方法传递的,则抛出错误。

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

在错误日志中,我的查询上面看起来很好。

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());
        }
    }

PreparedStatements有什么问题吗?

2 个答案:

答案 0 :(得分:2)

中删除参数
rs= pst.executeQuery(query);

更改为

rs= pst.executeQuery();

如果您将pst.executeQuery(query);中的查询作为参数传递,则此传递的query字符串优先于您在query中传递的conn.prepareStatement(query);字符串,因为在query中(select * from linkedin_page_messages where company_id = ?)你dint传递参数就会得到错误。

答案 1 :(得分:1)

删除此行中的参数:

rs= pst.executeQuery(query);

一定是

rs= pst.executeQuery();

因为该声明是在PreparedStatement pst=conn.prepareStatement(query);

准备的

execute(String sql)继承自Statement并将执行satement(sql)而不做好准备。