准备好的语句参数问题

Posted

技术标签:

【中文标题】准备好的语句参数问题【英文标题】:Prepared Statement Parameter Problems 【发布时间】:2013-09-18 13:00:36 【问题描述】:

我想要一个 Java 方法从我的 Oracle 11g 数据库中提取记录,但是我遇到了一些麻烦,因为我没有返回任何记录。如果我通过取消注释第 4 行和注释第 5 行和第 7 行来对值进行硬编码,result 将填充一条记录。没有捕获到异常。我错过了什么?

    conn = DriverManager.getConnection(url,props);

    String sql = "select col1, col2, col3"
              + " from table1"
             // + " where user_id = 'user123'"; // line 4
              + " where user_id = ?"; // line 5

    PreparedStatement preStatement = conn.prepareStatement(sql);

    preStatement.setString(1, "user123"); // line 7

    ResultSet result = preStatement.executeQuery();

    while(result.next()) 
        System.out.println("works");
    

【问题讨论】:

尝试打印出preStatement 对象,它应该会为您提供它将执行的确切查询。这可能会给我们一个提示。 【参考方案1】:

在查询中使用 trim() 函数。它可能与表的数据问题有关。

String sql = "select col1, col2, col3"
+ " from table1"
+ " where trim(user_id) = ?"; // line 5

在问号 (?) 符号后留有空格。

【讨论】:

以上是关于准备好的语句参数问题的主要内容,如果未能解决你的问题,请参考以下文章

了解 PDO 准备好的语句和绑定参数

JDBC驱动程序为准备好的语句转义参数?

如何使用准备好的语句动态绑定参数?

在准备好的语句参数中使用表列

如何使用准备好的 PDO 语句设置 ORDER BY 参数?

如何使用准备好的 PDO 语句设置 ORDER BY 参数?