jdbc关闭连接读取数据

因为我们对数据库访问一般会写一个能用dao,但是在调用的时候会返回一个数据集ResultSet ,

这个时候关闭数据库连接就不能读取ResultSet ,故有以下代码

在javax中有一个数据集缓冲器CachedRowSet,用他可以实现关闭连接读取数据,

跟ResultSet 一样方便

package sqltest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;

import javax.sql.rowset.*;

import com.sun.rowset.CachedRowSetImpl;

import java.util.Properties;

public class BaseDao {
 private Connection connection = null;

 private PreparedStatement pstmt = null;

 private ResultSet rs = null;

 /*
  * 返回数据库连接
  */
 public Connection getConnection() {
  try {
   Class.forName(getStrings().getProperty("driver"));
   connection = DriverManager.getConnection(getStrings().getProperty(
     "url"), getStrings().getProperty("username"), getStrings()
     .getProperty("password"));
  } catch (ClassNotFoundException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  } catch (SQLException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  }
  return connection;
 }

 /*
  * 读取配置文件
  */
 public Properties getStrings() {
  Properties properties = new Properties();
  try {
   properties.load(new FileInputStream("db.properties"));
  } catch (FileNotFoundException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  } catch (IOException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  } finally {
  }
  return properties;
 }

 /*
  * 读取表
  */
 public CachedRowSet getTable() {
  CachedRowSet cacheRowSet = null;
  try {
   cacheRowSet = new CachedRowSetImpl();
  } catch (SQLException e1) {
   // TODO 自动生成 catch 块
   e1.printStackTrace();
  }
  String sql = "select * from news";
  getConnection();
  try {
   pstmt = connection.prepareStatement(sql);
   rs = pstmt.executeQuery();
   cacheRowSet.populate(rs);
  } catch (SQLException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  } finally {
   try {
    connection.close();
   } catch (SQLException e) {
    // TODO 自动生成 catch 块
    e.printStackTrace();
   }
  }

  return cacheRowSet;
 }

 public static void main(String[] args) {
  BaseDao baseDao = new BaseDao();
  CachedRowSet cacheRowSet = baseDao.getTable();
  try {

   // ResultSetMetaData rsMd=rs.getMetaData();

   // RowSetMetaDataImpl rowSet=rsMd.;
   // rowSet.

   while (cacheRowSet.next()) {
    for (int i = 1; i <= 2; i++) {
     System.out.println(cacheRowSet.getObject(i));
    }
   }
  } catch (SQLException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  }
 }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值