一尘不染

PreparedStatement引发语法错误

mysql

我使用PreparedStatements准备查询,当我使用condition参数对查询进行硬编码时,它运行良好。

但如果从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有什么问题吗?


阅读 395

收藏
2020-05-17

共1个答案

一尘不染

删除此行中的参数:

rs= pst.executeQuery(query);

一定是

rs= pst.executeQuery();

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

execute(String sql)是从Statement继承的,将在不准备状态的情况下执行状态(sql)。

2020-05-17