⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dbconnection.java

📁 教师办公管理系统
💻 JAVA
字号:
package to.model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Vector;
import sun.jdbc.odbc.JdbcOdbcDriver;

public class DBConnection 
{
  
  
  //正在使用连接的数量
  private int using;
  //目前可用的连接数,即空闲连接
  private Vector connections=new Vector();
  //最大连接数
  private int maxconn;
  //连接池名
  private String poolname;


  //初使化以上所有私有成员
  public DBConnection(String poolname,int maxconn)
  {
    this.poolname=poolname;
    this.maxconn=maxconn;
  }//end method DBConnection()
  
  
  //返回所有连接
  public synchronized void returnConnection(Connection conn)
  {
    this.connections.addElement(conn);
    this.using--;
  }//end method returnConnection()
  
  
  //从连接池得到一个连接
  public synchronized Connection getConnection()
  {
    Connection conn=null;
     //connections是一个向量,用于存储连接对象,它所存储是的所有空闲状态的可用连接
    if(this.connections.size()>0)
    {
       //获取连接列表的第一个连接
      conn=(Connection)connections.elementAt(0);
      //获得一个连接,并将此连接从队列中删除.
      connections.removeElementAt(0);
       //如果此连接已关闭,刚继续获取,
      try
      {
        if(conn.isClosed())
        {
          conn=getConnection();
        }//end block if
      
      }//end block try
      catch(Exception e)
      {
        e.printStackTrace();
      }//end block catch
    }//end block if(this.connections.size()>0)
    //如果实际使用的连接数小于最大连接数即有可用连接,就新增加一个连接
    else if(maxconn==0||using<maxconn)
    {
      //如此时无可用连接(maxconn == 0)且连接数又未达到上限(using < maxconn)),就创建一个新连接
        conn=newConnection(); 
    }
    //如果连接数已达到上限就返回空指针
    if (conn!=null)
      {
        using++;
      }
    return conn;
  }//end method getConnection()
 
 
  //创建一个新的连接
  public Connection newConnection()
  {
    Connection conn=null;
    try
    {
      DriverManager.registerDriver(new JdbcOdbcDriver());
      conn=DriverManager.getConnection("jdbc:odbc:DBTeacher","sa","yjfnyv");
      return conn;
    }//end block try
    catch(Exception e)
    {
      return null;
    }//end block catch
  }//end method newConnection()
  
  
  //关闭所有连接
  public synchronized void closeConn()
  {
    Enumeration allConnections=connections.elements();
    while(allConnections.hasMoreElements())
    {
      Connection conn=(Connection)allConnections.nextElement();
      try
      {
        conn.close();
      }//end block try
      catch(SQLException e)
      {
        e.printStackTrace();
      }//end block catch
    }//end block while
    connections.removeAllElements();
  }//end method closeConn()

}//end class DBConnection

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -