字符串参数插入预准备语句的问题

时间:2010-02-19 12:04:20

标签: sql-server jdbc odbc prepared-statement

我有一个在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)进行插入。

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

提前致谢。

2 个答案:

答案 0 :(得分:0)

你在'?'

插入了什么?

如果您要插入

test

然后这将导致

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

哪个会失败。如果您要插入

"test"

然后这将导致

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

哪个会失败。 你需要插入

'test'

然后这将导致

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

这应该有用。

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

答案 1 :(得分:0)

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

现在,我编写了folling方法。它在编译语句之前使用字符串操作将字符串类型参数插入到语句中。 您应该使用参数index作为键并将值作为参数本身来构建参数映射。

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;
}
相关问题