JDBC的prepareStatement使用疑惑
改写分页程序,遇到一个SQL语句执行的问题,弄了一晚上也没解决。
public ArrayList findAllBooks(int offset, int length, Connection conn) throws SQLException {
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList books = new ArrayList();
BookDAO empvo = null;
BookVO bookVO=new BookVO();
// String strSql = "select * from book where rowid not in (select rowid from book where rownum >= ?) and rownum <= ?";//原来oracle的,现在不能用到sql server上
String strSql = "select top ? * "
+"from book "
+"where bookid not in "
+"(select top ? bookid "
+" from book )";
try {
ps = conn.prepareStatement(strSql);
ps.setByte(2, Integer.valueOf(length).byteValue()); //起始记录的位置
ps.setByte(1, Integer.valueOf(offset).byteValue()); //需要读取的记录数
rs = ps.executeQuery();
while (rs.next()) {
bookVO.setBookId(Integer.toString(rs.getInt ("BookID"))) ;
bookVO.setBookName (rs.getString ("BookName")) ;
bookVO.setAuthor(rs.getString ("Author")) ;
books.add(empvo);
}
}
catch (SQLException ex) {
ex.printStackTrace();
throw ex;
}
return books;
}
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]第 1
行: '@P1' 附近有语法错误。
at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source)
at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRequest.processErrorToken(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRequest.processReplyToken(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRPCRequest.processReplyToken(Unknown Source)
at com.microsoft.jdbc.sqlserver.tds.TDSRequest.processReply(Unknown Source)
at com.microsoft.jdbc.sqlserver.SQLServerImplStatement.getNextResultType(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.commonTransitionToState(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.postImplExecute(Unknown Source)
at com.microsoft.jdbc.base.BasePreparedStatement.postImplExecute(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.commonExecute(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.executeQueryInternal(Unknown Source)
at com.microsoft.jdbc.base.BasePreparedStatement.executeQuery(Unknown Source)
at com.fxfeiyi.itbook.dao.book.BookDAO.findAllBooks(BookDAO.java:47)
at com.fxfeiyi.itbook.bo.book.BookBO.findAllBooks(BookBO.java:33)