java - 如何使用 CachedRowSet 进行 SQL 查询?

标签 java mysql jdbc

我正在尝试使用 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/

相关文章:

mysql - 为什么 Django 的 __regex 没有像我想象的那样工作?

mysql - MySQL 存储过程的多态替代方案

C# 显示sql数据库中的字符串

java - 由 : java. lang.NoSuchMethodError : org.quartz.JobDataMap.put(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object 引起

Java:具有彼此实例的类

java - 如何访问 <s :iterator> tag of jsp file inside my javascript function? 中指定的自定义类对象的 java 列表

Java MySQL - 简单 MySQL 登录框架中的未知空指针异常

Java三元运算符和设置循环索引值

java - 从 Oracle 数据库 JDBC 中减去并更新值

mysql - "You have an error in your SQL syntax"