[英]Java + SQL Server: Resultset is null?
I am new to using java with a database and I have been trying following code: 我不熟悉将java与数据库一起使用,并且一直在尝试以下代码:
public int getDateDiff(int OrderID) {
Connection conn = DBConnection.getConnection();
Integer diff = null;
String getdiffSQL = "SELECT DATEDIFF( DAY , StartDate , EndDate ) FROM CarOrder WHERE OrderID = ?;";
try {
PreparedStatement pstm = conn.prepareStatement(getdiffSQL);
pstm.setInt(1, OrderID);
ResultSet rs = pstm.executeQuery(getdiffSQL);
while (rs.next()) {
diff = rs.getInt(1);
}
}
catch (SQLException ex) {
System.out.println("Error: " + ex.getMessage());
}
return diff;
}
I tried running this but i encounter this 我尝试运行此但遇到
"Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" “线程“ AWT-EventQueue-0”中的异常java.lang.NullPointerException”
and the the return diff is null. 并且return diff为null。 Please tell me what wrong in this and how do i fix this. 请告诉我这有什么问题以及如何解决。
PreparedStatement#executeQuery()
does not take a parameter and you should not be passing the query string. PreparedStatement#executeQuery()
不带参数,因此您不应传递查询字符串。 Instead use this pattern: 而是使用以下模式:
PreparedStatement pstm = conn.prepareStatement(getdiffSQL);
pstm.setInt(1, OrderID);
ResultSet rs = pstm.executeQuery(); // no parameter
This is a fairly common mistake made when using JDBC, partly because Statement#executeQuery()
does take the query string as a parameter. 使用JDBC时,这是一个相当普遍的错误,部分原因是Statement#executeQuery()
确实将查询字符串作为参数。 Add to this tutorials like MkYong which make the same mistake as the OP and it is easy to see why this error is so prevalant. 像MkYong这样的教程添加了与OP相同的错误,并且很容易理解为什么这个错误如此普遍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.