java - 使用 PreparedStatement 模板问题

标签 java jdbc prepared-statement

这是我的静态实用程序:

 //String sqlQuery = "select count(name) as num from tbname where name = ?"
    //String name = "testString";

    private static int correct(Connection connection, String sqlQuery, String name) {
        int result = 0;
        PreparedStatement statatement = null;
        ResultSet rs = null;
        try {
            statatement = connection.prepareStatement(sqlQuery);
            statatement.setString(1, name);
            rs = statatement.executeQuery();
            while (rs.next()) {
                result = rs.getInt("num");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                statatement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage());
            }
            return result;
        }
    }

上面的方法返回 0(不正确的结果),但下面的方法返回 '1'(它工作正常,它是相同的 sql 查询):

//String sqlQuery = "select count(name) as num from tbname where name = 'testString'"

    private static int correct(Connection connection, String sqlQuery, String name) {
        int result = 0;
        PreparedStatement statatement = null;
        ResultSet rs = null;
        try {
            statatement = connection.prepareStatement(sqlQuery);
            rs = statatement.executeQuery();
            while (rs.next()) {
                result = rs.getInt("num");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                statatement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage());
            }
            return result;
        }
    }

能否请您给我任何建议,以便我解决问题。

PS:我不确定它是否重要,但实际的 streetName - 在 windows-1251 编码(俄语)文本中有一个名称。 PPS:数据库是Oracle 10。

最佳答案

这可能是字符集问题。根据Oracle JDBC Drivers release 10.1.0.2.0 (10g) README :

The following is a list of known problems/limitations:

  • If the database character set is AL32UTF8, you may see errors under the following circumstances:
    • accessing LONG and VARCHAR2 datatypes.
    • binding data with setString() and setCharacterStream().

因此,如果您的数据库字符集是 AL32UTF8,您可能需要将其更改为其他字符集。

此外,您的列的数据类型是什么? VARCHAR2?

关于java - 使用 PreparedStatement 模板问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5026769/

相关文章:

java - 在hadoop中运行此程序时出错

java - 如何从 URL 检索图像并将其存储为 Java 中的 Blob(谷歌应用引擎)

java - 识别 JDBC 中的executeBatch()失败

php - PDO 准备语句未返回预期结果

java - 如何在Android中以纵向模式在Fragment中实现二维码扫描?

java - Azure 应用程序服务为 Spring Boot 应用程序提供 404

java - Netty中通过ServerBootstrap ChannelPipeline发送消息时出现UnsupportedOperationException

spring - 动态(运行时)更改 Spring Mybatis 中的数据源凭据

php - PDO PHP 使用 UNIX_TIMESTAMP() 准备和执行

php mysqli bind_param 错误参数计数