日期:2014-05-18  浏览次数:20661 次

菜鸟求可用的数据库连接池实例
网上找的DBConnectionManager   连接池在JSP页面中调用总出错。高手们给个数据连接池实例及页面调用方法。谢谢

------解决方案--------------------
用tomcat admin控制台建数据库连接迟,肯定没问题
------解决方案--------------------
自己写吧
------解决方案--------------------
package database;
import java.sql.*;
import sun.io.*;

public class sqlbean {
private Connection con;
private ResultSet rs;
public static Connection getConnection()throws SQLException{
try{
Class.forName( "com.microsoft.jdbc.sqlserver.SQLServerDriver ");

}catch(ClassNotFoundException ex)
{
ex.printStackTrace();
return null;
}
return DriverManager.getConnection( "jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=test ", "sa ", "sa ");



}

public ResultSet executeQuery(String sql){
try{
con=sqlbean.getConnection();
Statement statement=con.createStatement();
rs=statement.executeQuery(sql);
}
catch(SQLException ex)
{
System.out.print( "error ");
}
return rs;
}
public int executeUpdate(String sql)
{
int count=0;
Statement stmt=null;
try{
con=sqlbean.getConnection();
stmt=con.createStatement();
count=stmt.executeUpdate(sql);
}
catch(SQLException ex)
{

}
finally{
try{
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
}
catch(SQLException ex)
{
System.out.print(ex);
}
}
return count;
}
public void freeRs(ResultSet rs)
{
try
{
if(rs!=null)
{
rs.close();
con.close();
}
}
catch(Exception e)
{

}
}

}

------解决方案--------------------
看到很多人要数据库连接池,这里贴一个不需要配置tomcat的方案,方案中采用了Singleton模式要注意。
1.通用类ConnectionPool
package yourapplication.utility.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;

public class ConnectionPool implements Runnable {
private String driver, url, username, password;
private int maxConnections ;
private boolean waitIfBusy;
private Vector availableConnections, busyConnections;
private boolean connectionPending = false;

public ConnectionPool(String driver, String url,
String username, String password,
int initialConnections,
int maxConnections,
boolean waitIfBusy)
throws SQLException {
this.driver = driver;
this.url = url;
this.username = username;
this.password = password;
this.maxConnections = maxConnections;
this.waitIfBusy = waitIfBusy;
if (initialConnections > maxConnections) {
initialConnections = maxConnections;
}
availableConnections = new Vector(initialConnections);
busyConnections = new Vector();
for(int i=0; i <initialConnections; i++) {
availableConnections.addElement(makeNewConnec