首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用CachedRowSet进行SQL查询?

如何使用CachedRowSet进行SQL查询?
EN

Stack Overflow用户
提问于 2015-11-10 07:23:01
回答 2查看 1.6K关注 0票数 3

我正在尝试编写一个使用CachedRowSet进行SQl查询的方法。示例代码如下(前面定义了用户和密码),

代码语言:javascript
复制
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;
}

当我试图使用示例代码读取数据时,我一无所获。

代码语言:javascript
复制
CachedRowSet myValues =  getContentsOfCoffeesTable( myConn );
while( myValues != null && myValues.next() ){

     // get the values of 2nd column of the table 
     System.out.println( myValues.getString(2) );
}

咖啡桌已经有人了。如何改进代码?谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-11-10 22:31:59

我找到了如何使用CachedRowSet进行SQL查询的解决方案,并对该方法进行了如下更改:

代码语言:javascript
复制
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;
 }

然后,可以打印以下值,

代码语言:javascript
复制
// 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
EN

Stack Overflow用户

发布于 2015-11-18 06:07:56

我找到了另一种方法。在最初的帖子中,网址信息未按以下方式提供,

代码语言:javascript
复制
cr.setUrl(url);

其中网址的价值,

代码语言:javascript
复制
url = "jdbc:mysql://localhost:3306/myDemo"

该方法如下,

代码语言:javascript
复制
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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33624763

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档