jdbc关闭连接读取数据

来源:互联网 发布:mac玫瑰红brave red 编辑:程序博客网 时间:2024/05/05 12:14

因为我们对数据库访问一般会写一个能用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();
  }
 }
}

 

 

原创粉丝点击