我尝试使用 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表。我该如何改进代码?感谢。
答案 0 :(得分:1)
我找到了如何使用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;
}
然后,可以打印下面的值,
// 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) );
}
答案 1 :(得分:0)
我找到了另一种方法。在最初的帖子 url 中没有提供如下信息,
cr.setUrl(url);
url 的值,
url = "jdbc:mysql://localhost:3306/myDemo"
方法如下,
private CachedRowSet getContentsOfCoffeesTable(Connection con)
throws SQLException {
CachedRowSet cr = null;
try {
cr = new CachedRowSetImpl();
cr.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
cr.setConcurrency(ResultSet.CONCUR_UPDATABLE);
cr.setUsername(username);
cr.setPassword(password);
cr.setUrl(url);
cr.setCommand("select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES");
cr.execute();
}
catch (Exception ex) {
ex.printStackTrace();
}
return cr;
}