2010-02-19 47 views
1

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

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

在此先感谢。

回答

0

你在'?'插入什么?

如果插入

test 

,那么这将导致

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

将失败。如果插入

"test" 

,那么这将导致

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

将失败。 你需要插入

'test' 

,那么这将导致

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

这应该工作。

我不知道为什么=“测试”的作品,它不应该除非你有一个名为测试的专栏。

+0

感谢您的回答。我使用String对象,如:String s =“test”。我使用preparedStatement.setString(int index,String x)进行插入。它不是自动执行报价吗? – c0d3x 2010-02-19 13:21:47

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; 
}