我正在尝试使用 CachedRowSet 编写一个方法来执行 SQl 查询。示例代码如下(之前定义了用户和密码),
public CachedRowSet getContentsOfCoffeesTable( Connection connection ) throws SQLException {
CachedRowSet crs = null;
try {
crs = new CachedRowSetImpl();
crs.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
crs.setConcurrency(ResultSet.CONCUR_UPDATABLE);
crs.setUsername(user);
crs.setPassword(password);
crs.setCommand("select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES");
crs.execute();
} catch (SQLException e) {
e.printStackTrace();
}
return crs;
}
当我尝试使用示例代码读取数据时,我什么也没得到。
CachedRowSet myValues = getContentsOfCoffeesTable( myConn );
while( myValues != null && myValues.next() ){
// get the values of 2nd column of the table
System.out.println( myValues.getString(2) );
}
COFFEES 表已经填充。我怎样才能改进代码?谢谢。
最佳答案
我找到了如何使用 CachedRowSet 进行 SQL 查询的解决方案,并将方法更改如下,
public CachedRowSet getContentsOfCoffeesTable(Connection mycConn)
throws SQLException {
CachedRowSet crs = null;
ResultSet resultSet = null;
Statement stmt = null;
String sql = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";
try {
stmt = myConn.createStatement();
resultSet = stmt.executeQuery(sql);
crs = new CachedRowSetImpl();
crs.populate(resultSet);
}
catch (Exception e) {
e.printStackTrace();
}
return crs;
}
然后,可以打印以下值 s,
// I get the Connection myConn here
// then pass the connection info to the method and get myValues
// prit myValues for column index of 2
CachedRowSet myValues = getContentsOfCoffeesTable( myConn );
while( myValues != null && myValues.next() ){
// get the values of 2nd column of the table
System.out.println( myValues.getString(2) );
}
关于java - 如何使用 CachedRowSet 进行 SQL 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33624763/