关于数据库连接
2024-07-21 02:06:39
供稿:网友
 
对于数据库的连接,有一些共性的东西;积累了几个方法,可以作为一个可复用的模块。
/********************************************************************/
  类jbfcmsconnect :
import java.io.*;
import java.util.*;
import java.sql.*;
import java.text.*;
import java.lang.*;
/**
 * @author  *
 * to change this generated comment edit the template variable "typecomment":
 * window>preferences>java>templates.
 * to enable and disable the creation of type comments go to
 * window>preferences>java>code generation.
 */
public class jbfcmsconnect {
 private string drive = "";
 private string dburl = "";
 private string prop_server_name = "";
 private string prop_db_name = "";
 private string dbusername = "";
 private string dbuserpassword = "";
        private string prop_db_provider;
 /**
  *  onstructor for dbconnect
  */
 public jbfcmsconnect() {
  init();
 }
 /**
  * method init.
  */
 private void init() {
system.out.println("enter init");
  properties defaultsettings = new properties();
  defaultsettings.put("db_name", "jbmms");
  defaultsettings.put("db_provider","db2");
  defaultsettings.put("username", "root");
  defaultsettings.put("passwerd", " ");
  defaultsettings.put("driver_type", "net");
system.out.println("put default settings");
  string prop_driver_type = defaultsettings.getproperty("driver_type");
  prop_db_name = defaultsettings.getproperty("db_name");
  prop_db_provider=defaultsettings.getproperty("db_provider");
  dbusername = defaultsettings.getproperty("username");
  dbuserpassword = defaultsettings.getproperty("password");
system.out.println("set default settings");
  properties settings = new properties();
  try {
system.out.println("start search properties file");
   fileinputstream sf = new fileinputstream("c://jbfcmsconnect.prop");
   settings.load(sf);
   prop_driver_type = settings.getproperty("driver_type");
   prop_db_name = settings.getproperty("db_name");
   prop_db_provider=settings.getproperty("db_provider");
   dbusername = settings.getproperty("username");
   dbuserpassword = settings.getproperty("password");
   prop_server_name = settings.getproperty("server_name");
   sf.close();
   system.out.println("properties file exist");
  } catch (filenotfoundexception e) {
   system.out.println("properties file was not found!");
  } catch (ioexception e) {
   system.out.println("ioexception is found!");
  }
  /////////////////
  if (prop_db_provider.equalsignorecase("db2"))
 { if(prop_driver_type.equalsignorecase("net"))
     {     //system.out.println("be in-----");
  drive="com.ibm.db2.jdbc.net.db2driver";
  string prop_server_name=settings.getproperty("server_name");
  dburl="jdbc:db2://" + prop_server_name + "/" + prop_db_name;
     }else{
  drive="com.ibm.db2.jdbc.app.db2driver";
  dburl="jdbc:db2:" + prop_db_name;
     }
 system.out.println("db2 connection ==> /n drivername="+ drive + "/n url="+dburl+"/n");}
 //mysql数据库连接
 else if (prop_db_provider.equalsignorecase("mysql"))
 { if(prop_driver_type.equalsignorecase("net"))
 {
  drive="com.mysql.jdbc.driver";
  string prop_server_name=settings.getproperty("server_name");
  dburl="jdbc:mysql://" + prop_server_name + "/" + prop_db_name;
 }else{
  drive="com.mysql.jdbc.driver";
  dburl="jdbc:mysql:" + prop_db_name;
 }
 system.out.println("mysql connection ==> /n drivername="+ drive + "/n url="+dburl+"/n");}
 //sqlserver数据库连接
 else if(prop_db_provider.equalsignorecase("sqlserver"))
 {if(prop_driver_type.equalsignorecase("net"))
 {
  drive="com.microsoft.jdbc.sqlserver.sqlserverdriver";
  string prop_server_name=settings.getproperty("server_name");
  dburl="jdbc:microsoft:sqlserver://" + prop_server_name + "/" + prop_db_name;
 }else{
  drive="com.microsoft.jdbc.sqlserver.sqlserverdriver";
  dburl="jdbc:microsoft:sqlserver://" + prop_db_name;
 }
 system.out.println("sqlserver connection ==> /n drivername="+ drive + "/n url="+dburl+"/n");}
 }
 connection conn = null;
 private void connectpool() {
  try {
   class.forname(drive).newinstance();
   conn =
    drivermanager.getconnection(dburl, dbusername, dbuserpassword);
  } catch (classnotfoundexception ec) {
   system.out.println("数据库驱动装载存在问题");
  } catch (illegalaccessexception ei) {
   system.out.println("数据库访问异常");
  } catch (instantiationexception ei) {
   system.out.println(ei.getmessage());
  } catch (sqlexception e) {
   system.out.println(
    "/n***********************数据库连接异常**********************/n");
   while (e != null) {
    system.out.println("sqlstate:" + e.getsqlstate());
    system.out.println("message:" + e.getmessage());
    system.out.println("vendor:" + e.geterrorcode());
    e = e.getnextexception();
   }
  }
 }
 public connection getconnect() {
  connectpool();
  return conn;
 }
}
//此类负责数据库的连接部分
类:jbsqlexecute 
import java.io.*;
import java.util.*;
import java.util.date;
import java.sql.*;
import java.text.*;
 
/**
 * @author
 *
 * to change this generated comment edit the template variable "typecomment":
 * window>preferences>java>templates.
 * to enable and disable the creation of type comments go to
 * window>preferences>java>code generation.
 */
public class jbsqlexecute {
 private static connection con = null;
 private preparedstatement pstmt = null;
 /**
  * constructor for jbsqlexecute.
  */
 public jbsqlexecute() {
  jbfcmsconnect connect = new jbfcmsconnect();
  con = connect.getconnect();
 }
 
 /**
  * method sqlinsert.
  * @param strinsert
  * @
  */
 public void sqlinsert(string strinsert) {
  try {
   pstmt = con.preparestatement(strinsert);
   pstmt.execute();
  } catch (sqlexception sqle) {
   system.out.println("jbmms数据库插入异常:" + sqle.getmessage());
  }
 }
 /**
  * method strupdata.
  * @param strupdata
  * @
  */
 public void sqlupdata(string strupdata) {
  try {
   pstmt = con.preparestatement(strupdata);
   pstmt.execute();
  } catch (sqlexception sqle) {
   system.out.println("jbmms数据库更新异常:" + sqle.getmessage());
  }
 }
 /**
  * method executequery.
  * @param strquery
  * @return resultset
  */
 public resultset executequery(string strquery) {
  resultset rset = null;
  try {
   system.out.println(strquery);
   pstmt = con.preparestatement(strquery);
   rset=pstmt.executequery();
   system.out.println("over");
  } catch (sqlexception sqle) {
   system.out.println("jbmms数据库查询异常:" + sqle.getmessage());
  }
  system.out.println("rset");
  return rset;
 }
 
 /**
  * method executedelete.
  * @param strdelete
  */
 public void executedelete(string strdelete) {
  try {
   pstmt = con.preparestatement(strdelete);
   pstmt.execute();
  } catch (sqlexception sqle) {
   system.out.println("jbmms数据库删除异常:" + sqle.getmessage());
  }
 }
}
//数据库操作的执行,在使用时直接调用此类中的方法即可。
/******************************************************************/
 一个关于数据库连接池的实现---借鉴于网友
源代码 
//connectionpool.java 
package com.abner.dbconnector; 
import java.sql.*; 
import java.util.*; 
/** 
* connectionpool 类创建了一个对特定数据库指定大小的连接池。连接池对象 
* 允许客户端指定 jdbc 驱动程序,数据库,使用数据库的用户名和密码。而且, 
* 客户端能指定连接池的在初始创建是产生数据库连接的数量,和指定当连接 
* 不够时每次自动增加连接的数量及连接池最多的数据库连接的数量。 
* 
* 对外提供的方法有: connectionpool :构造函数 
* getinitialconnections: 返回连接池初始化大小 
* setinitialconnections: 设置连接池初始化大小 
* getincrementalconnections: 返回连接池自动增加的增量 
* setincrementalconnections: 设置连接池自动增加的大小 
* getmaxconnections :获得连接池的最大可允许的连接数 
* setmaxconnections :设置连接池的最大可允许的连接数 
* gettesttable :获得测试表的名字 
* settesttable :设置测试表的名字 
* createpool: 创建连接池 , 线程己同步 
* getconnection: 从连接池中获得一个数据库连接 
* returnconnection: 返回一个连接到连接池中 
* refreshconnections: 刷新连接池 
* closeconnectionpool: 关闭连接池 
* 
*/ 
public class connectionpool { 
private string jdbcdriver = ""; // 数据库驱动 
private string dburl = ""; // 数据 url 
private string dbusername = ""; // 数据库用户名 
private string dbpassword = ""; // 数据库用户密码 
private string testtable = ""; // 测试连接是否可用的测试表名,默认没有测试表 
private int initialconnections = 10; // 连接池的初始大小 
private int incrementalconnections = 5;// 连接池自动增加的大小 
private int maxconnections = 50; // 连接池最大的大小 
private vector connections = null; // 存放连接池中数据库连接的向量 , 初始时为 null 
// 它中存放的对象为 pooledconnection 型 
/** 
* 构造函数 
* 
* @param jdbcdriver string jdbc 驱动类串 
* @param dburl string 数据库 url 
* @param dbusername string 连接数据库用户名 
* @param dbpassword string 连接数据库用户的密码 
* 
*/ 
public connectionpool(string jdbcdriver,string dburl,string dbusername,string dbpassword) { 
this.jdbcdriver = jdbcdriver; 
this.dburl = dburl; 
this.dbusername = dbusername; 
this.dbpassword = dbpassword; 
} 
/** 
* 返回连接池的初始大小 
* 
* @return 初始连接池中可获得的连接数量 
*/ 
public int getinitialconnections() { 
return this.initialconnections; 
} 
/** 
* 设置连接池的初始大小 
* 
* @param 用于设置初始连接池中连接的数量 
*/ 
public void setinitialconnections(int initialconnections) { 
this.initialconnections = initialconnections; 
} 
/** 
* 返回连接池自动增加的大小 、 
* 
* @return 连接池自动增加的大小 
*/ 
public int getincrementalconnections() { 
return this.incrementalconnections; 
} 
/** 
* 设置连接池自动增加的大小 
* @param 连接池自动增加的大小 
*/ 
public void setincrementalconnections(int incrementalconnections) { 
this.incrementalconnections = incrementalconnections; 
} 
/** 
* 返回连接池中最大的可用连接数量 
* @return 连接池中最大的可用连接数量 
*/ 
public int getmaxconnections() { 
return this.maxconnections; 
} 
/** 
* 设置连接池中最大可用的连接数量 
* 
* @param 设置连接池中最大可用的连接数量值 
*/ 
public void setmaxconnections(int maxconnections) { 
this.maxconnections = maxconnections; 
} 
/** 
* 获取测试数据库表的名字 
* 
* @return 测试数据库表的名字 
*/ 
public string gettesttable() { 
return this.testtable; 
} 
/** 
* 设置测试表的名字 
* @param testtable string 测试表的名字 
*/ 
public void settesttable(string testtable) { 
this.testtable = testtable; 
} 
/** 
* 
* 创建一个数据库连接池,连接池中的可用连接的数量采用类成员 
* initialconnections 中设置的值 
*/ 
public synchronized void createpool() throws exception { 
// 确保连接池没有创建 
// 如果连接池己经创建了,保存连接的向量 connections 不会为空 
if (connections != null) { 
return; // 如果己经创建,则返回 
} 
// 实例化 jdbc driver 中指定的驱动类实例 
driver driver = (driver) (class.forname(this.jdbcdriver).newinstance()); 
drivermanager.registerdriver(driver); // 注册 jdbc 驱动程序 
// 创建保存连接的向量 , 初始时有 0 个元素 
connections = new vector(); 
// 根据 initialconnections 中设置的值,创建连接。 
createconnections(this.initialconnections); 
system.out.println(" 数据库连接池创建成功! "); 
} 
/** 
* 创建由 numconnections 指定数目的数据库连接 , 并把这些连接 
* 放入 connections 向量中 
* 
* @param numconnections 要创建的数据库连接的数目 
*/ 
private void createconnections(int numconnections) throws sqlexception { 
// 循环创建指定数目的数据库连接 
for (int x = 0; x < numconnections; x++) { 
// 是否连接池中的数据库连接的数量己经达到最大?最大值由类成员 maxconnections 
// 指出,如果 maxconnections 为 0 或负数,表示连接数量没有限制。 
// 如果连接数己经达到最大,即退出。 
if (this.maxconnections > 0 && this.connections.size() >= this.maxconnections) { 
break; 
} 
//add a new pooledconnection object to connections vector 
// 增加一个连接到连接池中(向量 connections 中) 
try{ 
connections.addelement(new pooledconnection(newconnection())); 
}catch(sqlexception e){ 
system.out.println(" 创建数据库连接失败! "+e.getmessage()); 
throw new sqlexception(); 
} 
system.out.println(" 数据库连接己创建 ......"); 
} 
} 
/** 
* 创建一个新的数据库连接并返回它 
* 
* @return 返回一个新创建的数据库连接 
*/ 
private connection newconnection() throws sqlexception { 
// 创建一个数据库连接 
connection conn = drivermanager.getconnection(dburl, dbusername, dbpassword); 
// 如果这是第一次创建数据库连接,即检查数据库,获得此数据库允许支持的 
// 最大客户连接数目 
//connections.size()==0 表示目前没有连接己被创建 
if (connections.size() == 0) { 
databasemetadata metadata = conn.getmetadata(); 
int drivermaxconnections = metadata.getmaxconnections(); 
// 数据库返回的 drivermaxconnections 若为 0 ,表示此数据库没有最大 
// 连接限制,或数据库的最大连接限制不知道 
//drivermaxconnections 为返回的一个整数,表示此数据库允许客户连接的数目 
// 如果连接池中设置的最大连接数量大于数据库允许的连接数目 , 则置连接池的最大 
// 连接数目为数据库允许的最大数目 
if (drivermaxconnections > 0 && this.maxconnections > drivermaxconnections) { 
this.maxconnections = drivermaxconnections; 
} 
} 
return conn; // 返回创建的新的数据库连接 
} 
/** 
* 通过调用 getfreeconnection() 函数返回一个可用的数据库连接 , 
* 如果当前没有可用的数据库连接,并且更多的数据库连接不能创 
* 建(如连接池大小的限制),此函数等待一会再尝试获取。 
* 
* @return 返回一个可用的数据库连接对象 
*/ 
public synchronized connection getconnection() throws sqlexception { 
// 确保连接池己被创建 
if (connections == null) { 
return null; // 连接池还没创建,则返回 null 
} 
connection conn = getfreeconnection(); // 获得一个可用的数据库连接 
// 如果目前没有可以使用的连接,即所有的连接都在使用中 
while (conn == null){ 
// 等一会再试 
wait(250); 
conn = getfreeconnection(); // 重新再试,直到获得可用的连接,如果 
//getfreeconnection() 返回的为 null 
// 则表明创建一批连接后也不可获得可用连接 
} 
return conn;// 返回获得的可用的连接 
} 
/** 
* 本函数从连接池向量 connections 中返回一个可用的的数据库连接,如果 
* 当前没有可用的数据库连接,本函数则根据 incrementalconnections 设置 
* 的值创建几个数据库连接,并放入连接池中。 
* 如果创建后,所有的连接仍都在使用中,则返回 null 
* @return 返回一个可用的数据库连接 
*/ 
private connection getfreeconnection() throws sqlexception { 
// 从连接池中获得一个可用的数据库连接 
connection conn = findfreeconnection(); 
if (conn == null) { 
// 如果目前连接池中没有可用的连接 
// 创建一些连接 
createconnections(incrementalconnections); 
// 重新从池中查找是否有可用连接 
conn = findfreeconnection(); 
if (conn == null) { 
// 如果创建连接后仍获得不到可用的连接,则返回 null 
return null; 
} 
} 
return conn; 
} 
/** 
* 查找连接池中所有的连接,查找一个可用的数据库连接, 
* 如果没有可用的连接,返回 null 
* 
* @return 返回一个可用的数据库连接 
*/ 
private connection findfreeconnection() throws sqlexception { 
connection conn = null; 
pooledconnection pconn = null; 
// 获得连接池向量中所有的对象 
enumeration enum = connections.elements(); 
// 遍历所有的对象,看是否有可用的连接 
while (enum.hasmoreelements()) { 
pconn = (pooledconnection) enum.nextelement(); 
if (!pconn.isbusy()) { 
// 如果此对象不忙,则获得它的数据库连接并把它设为忙 
conn = pconn.getconnection(); 
pconn.setbusy(true); 
// 测试此连接是否可用 
if (!testconnection(conn)) { 
// 如果此连接不可再用了,则创建一个新的连接, 
// 并替换此不可用的连接对象,如果创建失败,返回 null 
try{ 
conn = newconnection(); 
}catch(sqlexception e){ 
system.out.println(" 创建数据库连接失败! "+e.getmessage()); 
return null; 
} 
pconn.setconnection(conn); 
} 
break; // 己经找到一个可用的连接,退出 
} 
} 
return conn;// 返回找到到的可用连接 
} 
/** 
* 测试一个连接是否可用,如果不可用,关掉它并返回 false 
* 否则可用返回 true 
* 
* @param conn 需要测试的数据库连接 
* @return 返回 true 表示此连接可用, false 表示不可用 
*/ 
private boolean testconnection(connection conn) { 
try { 
// 判断测试表是否存在 
if (testtable.equals("")) { 
// 如果测试表为空,试着使用此连接的 setautocommit() 方法 
// 来判断连接否可用(此方法只在部分数据库可用,如果不可用 , 
// 抛出异常)。注意:使用测试表的方法更可靠 
conn.setautocommit(true); 
} else {// 有测试表的时候使用测试表测试 
//check if this connection is valid 
statement stmt = conn.createstatement(); 
stmt.execute("select count(*) from " + testtable); 
} 
} catch (sqlexception e) { 
// 上面抛出异常,此连接己不可用,关闭它,并返回 false; 
closeconnection(conn); 
return false; 
} 
// 连接可用,返回 true 
return true; 
} 
/** 
* 此函数返回一个数据库连接到连接池中,并把此连接置为空闲。 
* 所有使用连接池获得的数据库连接均应在不使用此连接时返回它。 
* 
* @param 需返回到连接池中的连接对象 
*/ 
public void returnconnection(connection conn) { 
// 确保连接池存在,如果连接没有创建(不存在),直接返回 
if (connections == null) { 
system.out.println(" 连接池不存在,无法返回此连接到连接池中 !"); 
return; 
} 
pooledconnection pconn = null; 
enumeration enum = connections.elements(); 
// 遍历连接池中的所有连接,找到这个要返回的连接对象 
while (enum.hasmoreelements()) { 
pconn = (pooledconnection) enum.nextelement(); 
// 先找到连接池中的要返回的连接对象 
if (conn == pconn.getconnection()) { 
// 找到了 , 设置此连接为空闲状态 
pconn.setbusy(false); 
break; 
} 
} 
} 
/** 
* 刷新连接池中所有的连接对象 
* 
*/ 
public synchronized void refreshconnections() throws sqlexception { 
// 确保连接池己创新存在 
if (connections == null) { 
system.out.println(" 连接池不存在,无法刷新 !"); 
return; 
} 
pooledconnection pconn = null; 
enumeration enum = connections.elements(); 
while (enum.hasmoreelements()) { 
// 获得一个连接对象 
pconn = (pooledconnection) enum.nextelement(); 
// 如果对象忙则等 5 秒 ,5 秒后直接刷新 
if (pconn.isbusy()) { 
wait(5000); // 等 5 秒 
} 
// 关闭此连接,用一个新的连接代替它。 
closeconnection(pconn.getconnection()); 
pconn.setconnection(newconnection()); 
pconn.setbusy(false); 
} 
} 
/** 
* 关闭连接池中所有的连接,并清空连接池。 
*/ 
public synchronized void closeconnectionpool() throws sqlexception { 
// 确保连接池存在,如果不存在,返回 
if (connections == null) { 
system.out.println(" 连接池不存在,无法关闭 !"); 
return; 
} 
pooledconnection pconn = null; 
enumeration enum = connections.elements(); 
while (enum.hasmoreelements()) { 
pconn = (pooledconnection) enum.nextelement(); 
// 如果忙,等 5 秒 
if (pconn.isbusy()) { 
wait(5000); // 等 5 秒 
} 
//5 秒后直接关闭它 
closeconnection(pconn.getconnection()); 
// 从连接池向量中删除它 
connections.removeelement(pconn); 
} 
// 置连接池为空 
connections = null; 
} 
/** 
* 关闭一个数据库连接 
* 
* @param 需要关闭的数据库连接 
*/ 
private void closeconnection(connection conn) { 
try { 
conn.close(); 
}catch (sqlexception e) { 
system.out.println(" 关闭数据库连接出错: "+e.getmessage()); 
} 
} 
/** 
* 使程序等待给定的毫秒数 
* 
* @param 给定的毫秒数 
*/ 
private void wait(int mseconds) { 
try { 
thread.sleep(mseconds); 
} catch (interruptedexception e) { 
} 
} 
/** 
* 
* 内部使用的用于保存连接池中连接对象的类 
* 此类中有两个成员,一个是数据库的连接,另一个是指示此连接是否 
* 正在使用的标志。 
*/ 
class pooledconnection { 
connection connection = null;// 数据库连接 
boolean busy = false; // 此连接是否正在使用的标志,默认没有正在使用 
// 构造函数,根据一个 connection 构告一个 pooledconnection 对象 
public pooledconnection(connection connection) { 
this.connection = connection; 
} 
// 返回此对象中的连接 
public connection getconnection() { 
return connection; 
} 
// 设置此对象的,连接 
public void setconnection(connection connection) { 
this.connection = connection; 
} 
// 获得对象连接是否忙 
public boolean isbusy() { 
return busy; 
} 
// 设置对象的连接正在忙 
public void setbusy(boolean busy) { 
this.busy = busy; 
} 
} 
}