2015-11-10 82 views
3

我想写一个方法使用CachedRowSet做SQ1查询。示例代码如下(用户和密码早先定义),如何使用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表已被填充。我如何改进代码?谢谢。

+1

如果你设法解决你的问题,那么你不应该编辑你的问题来添加解决方案,而是应该用s发布答案olution。这对其他人来说更加清楚,并且也允许你接受你自己的答案。 –

+1

请注意,问题的原因是您没有提供到缓存行集(连接到行集本身或执行方法)的连接,因此它无法查询信息,因为它不会查询信息,没有联系。 –

+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

您需要清楚地说明您改变了什么才能使其工作。不只是代码转储。 – EJP

0

我找到另一种方式来做到这一点。在初始后网址信息未如下规定,

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; 
}