Oracle JDBC选择WHERE返回0

Koz*_*łek 2 java sql jdbc oracle10g

类似的问题: JDBC的奇怪问题,选择返回null 但人们没有要求这个.

我的代码:

public int myMethod(String day) throws SQLException{
  String sql = "Select count(*) from MyTable WHERE someColumn = " + day;
  Connection connection = ConnFactory.get();
  PreparedStatement prepareStatement = null;
  ResultSet resultSet = null;
  int ret = -1;
  try{
      prepareStatement = connection.prepareStatement(sql);
      resultSet = prepareStatement.executeQuery(sql);
      if(resultSet.next()){
          ret = resultSet.getInt(1);
      }
  }
  catch(SQLException sqle){
      // closing statement & ResultSet, log and throw exception
  }
  finally{
     // closing statement & ResultSet
  }
  ConnFactory.kill(connection);

  return ret;
}
Run Code Online (Sandbox Code Playgroud)

此代码始终返回0.我尝试在执行前记录sql并尝试在SQLdeveloper中运行它并获得正确的值(超过100).当我删除WHERE时,sql = "Select count(*) from MyTable查询表中所有行的返回数.我使用Oracle 10g和ojdbc-14.jar(来自maven repo的最新版本)和Java 6.

kar*_*m79 5

day没有被正确引用,我建议使用准备好的声明,准备好的声明如下:

...
try {
    prepareStatement = connection.prepareStatement("Select count(*) from MyTable WHERE someColumn = ?");
    prepareStatement.setString(1,day);
...
Run Code Online (Sandbox Code Playgroud)

是相同的:

sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";
Run Code Online (Sandbox Code Playgroud)

与后者相比具有几个优点(主要是安全性和性能).看到:

http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html