【问题标题】:Problems with string parameter insertion into prepared statement将字符串参数插入准备好的语句的问题
【发布时间】:2010-02-19 12:04:20
【问题描述】:

我有一个在 MS SQL Server 上运行的数据库。我的应用程序通过 JDBC 和 ODBC 与之通信。现在我尝试使用准备好的语句。

当我插入一个数字(长)参数时,一切正常。当我插入一个字符串 参数它不起作用。没有错误消息,但结果集为空。

WHERE column LIKE ('%' + ? + '%') --inserted "test" -> empty result set
WHERE column LIKE ? --inserted "%test%" -> empty result set
WHERE column = ? --inserted "test" -> works

但我需要 LIKE 功能。当我将相同的字符串直接插入查询字符串(不是作为准备好的语句参数)时,它运行良好。

WHERE column LIKE '%test%'

对我来说,它看起来有点像双引号,但我从未在字符串中使用引号。我使用preparedStatement.setString(int index, String x) 进行插入。

是什么导致了这个问题? 我该如何解决?

提前致谢。

【问题讨论】:

    标签: sql-server jdbc odbc prepared-statement


    【解决方案1】:

    你在“?”处插入什么

    如果你正在插入

    test
    

    那么这将导致

    WHERE column LIKE ('%' + test + '%')
    

    这将失败。如果你要插入

    "test"
    

    那么这将导致

    WHERE column LIKE ('%' + "test" + '%')
    

    这会失败。 你需要插入

    'test'
    

    那么这将导致

    WHERE column LIKE ('%' + 'test' + '%')
    

    这应该可以工作。

    我不知道为什么 = "test" 有效,除非您有一个名为 test 的列。

    【讨论】:

    • 感谢您的回答。我使用 String 对象,例如:String s = "test"。我使用preparedStatement.setString(int index, String x) 进行插入。它不会自动报价吗?
    【解决方案2】:

    我正在使用 SUN 的 JdbcOdbcBridge。据我所知,你应该避免使用它。也许那里有更好的实现。

    目前,我编写了以下方法。它在语句编译之前将字符串类型的参数插入到带有字符串操作的语句中。 您应该构建一个参数映射,以参数索引作为键,值作为参数本身。

    private static String insertStringParameters(String statement, Map<Integer, Object> parameters) {
        for (Integer parameterIndex : parameters.keySet()) {
            Object parameter = parameters.get(parameterIndex);
            if (parameter instanceof String) {
                String parameterString = "'" + (String) parameter + "'";
                int occurence = 0;
                int stringIndex = 0;
                while(occurence < parameterIndex){
                    stringIndex = statement.indexOf("?", stringIndex) + 1;
                    occurence++;
                }
                statement = statement.substring(0, stringIndex - 1) + parameterString + statement.substring(stringIndex);
            }
        }
        return statement;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      • 2019-02-13
      • 2017-01-22
      • 2011-07-13
      • 2014-06-30
      • 1970-01-01
      相关资源
      最近更新 更多