类似的问题: Strange problem with JDBC, select returns 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;
}
此代码始终返回0.我尝试在执行前记录sql并尝试在SQLdeveloper中运行它并获得正确的值(超过100)。
当我删除WHERE时,sql = "Select count(*) from MyTable
查询表中所有行的返回数。
我使用Oracle 10g和ojdbc-14.jar(来自maven repo的最新版本)和Java 6。
答案 0 :(得分:5)
day
未被正确引用,我建议使用预备语句,如准备好的声明,如下所示:
...
try {
prepareStatement = connection.prepareStatement("Select count(*) from MyTable WHERE someColumn = ?");
prepareStatement.setString(1,day);
...
与:
相同sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";
具有优于后者的几个优点(主要是安全性和性能)。参见:
http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html
答案 1 :(得分:4)
首先使用这样的sql是不可取的。因为它会导致SQL注入。
将来尝试使用如下所示并使用PreparedStatement执行
String sql = "Select count(*) from MyTable WHERE someColumn = ? "
您的解决方案是否尝试
String sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";
答案 2 :(得分:0)
karim79是个很好的答案,你忘了在你的“日期”值中添加撇号标记
String sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";