初始化数据库连接类(DB.java)

本文介绍了一个使用Struts框架进行数据库操作的Java类,包括连接池的配置、执行SQL查询及更新的方法,并展示了如何利用JDBC进行数据库交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package org.lzh.struts;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DB {
 /**connect*/
 Connection connect = null;
 /**结果集*/
 ResultSet rs = null;
 
 public DB(DataSource dataSource) { 
  try {
   /*通过数据源,初始化连接池*/
   connect = dataSource.getConnection();
  }
  catch(SQLException e) {
   e.printStackTrace();
  }
 }
 
 public ResultSet OpenSql(String sql) {
  try {
   /**
    * ResultSet.TYPE_SCROLL_INSENSITIVE
    * The constant indicating the type for a ResultSet object
    * that is scrollable but generally not sensitive to changes made by others.
    */
   /**
    * ResultSet.CONCUR_READ_ONLY
    * The constant indicating the concurrency mode for a ResultSet object that may NOT be updated.
    */
   Statement stmt = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
   rs = stmt.executeQuery(sql);
  }
  catch(SQLException ex) {
   ex.printStackTrace();
  }
  return rs;
 }
 
 public int ExecSql(String sql) {
  int result = 0;
  try {
   Statement stmt = connect.createStatement();
   result = stmt.executeUpdate(sql);
  }
  catch(SQLException ex) {
   System.err.println(ex.getMessage());
   
  }
  return result;
 }
 
 /**
  * 关闭数据库连接池
  *
  */
 public void close(){
  if(connect!=null){
   try{
    connect.close();
    connect = null; 
   }catch(SQLException ex) {
    System.err.println(ex.getMessage());
   }
  } 
 }
}

//数据库连接池的配置
<DATA-SOURCES>
    <DATA-SOURCE type="org.apache.commons.dbcp.BasicDataSource" key="dataSource">
      <SET-PROPERTY value="root" property="password" />
      <SET-PROPERTY value="3" property="minCount" />
      <SET-PROPERTY value="10" property="maxCount" />
      <SET-PROPERTY value="root" property="username" />
      <SET-PROPERTY value="com.mysql.jdbc.Driver" property="driverClassName" />
      <SET-PROPERTY value="strutsbbs" property="description" />
      <SET-PROPERTY value="jdbc:mysql://localhost:3306/strutsbbs" property="url" />
      <SET-PROPERTY value="false" property="readOnly" />
      <SET-PROPERTY value="true" property="autoCommit" />
    </DATA-SOURCE>
  </DATA-SOURCES> 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值