preparedstatement抛出语法错误

hc2pp10m  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(371)

这个问题在这里已经有答案了

尝试执行preparedstatement时,mysqlsyntaxerrorexception靠近“?”(2个答案)
5年前关门了。
我用preparedstatements准备一个查询,当我用条件参数硬编码te查询时,它运行良好。
但如果参数是从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());
        }
    }

准备好的报表有什么问题吗?

4ioopgfo

4ioopgfo1#

删除此行中的参数:

rs= pst.executeQuery(query);

一定是的

rs= pst.executeQuery();

因为这份声明是在
PreparedStatement pst=conn.prepareStatement(query); execute(String sql) 是从语句继承的,将执行satement(sql),而不准备它。

kh212irz

kh212irz2#

从中删除参数

rs= pst.executeQuery(query);

更改为

rs= pst.executeQuery();

如果你传入查询 pst.executeQuery(query); 作为参数,则此参数传递 query 字符串优先于 query 你传入的字符串 conn.prepareStatement(query); 从年开始 query ( select * from linkedin_page_messages where company_id = ? )你只要传递参数就得到了错误。

相关问题