有没有现成的数据库连接池程序?
各位大虾:
我要做一个web程序,主要是和数据库打交道。以前我连接数据库都需要一次连接一次,现我想改用数据库连接池,可不知道如何做?
谢谢先
[解决办法]
tomcat自带的。
[解决办法]
用tomcat自带的基本不用写程序获得连接了啊
lookup就可以
用完自动放回去
[解决办法]
是不是要这个??
import java.io.*;
import java.sql.*;
import java.util.*;
public class ConnectionPool {
static final int MAX_CONNECTION = 10;//最大连接数
static Vector connections = null;//存放连接
String hostname= "com.microsoft.jdbc.sqlserver.SQLServerDriver ";
String login= "sa ",password= " ";
String connectString = "jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=HotelManage ";
static ConnectionPool instance =null;
public static synchronized ConnectionPool getInstance()//实例化
{
if (instance ==null)
instance = new ConnectionPool();
return instance;
}
public synchronized void initialize()//初始化
{
if (connections == null)
try
{
Class.forName(hostname);
connections = new Vector();
int count =0;
while (count <MAX_CONNECTION)
{
Connection conn = DriverManager.getConnection(connectString, login, password);
connections.addElement(conn);
count++;
}
}catch(SQLException sqle){}catch(ClassNotFoundException cnfe){}
}
public synchronized Connection getConnection()//获得可用连接
{
Connection conn = null;
if(connections == null)
return null;
if(connections.size()> 0)
{
conn=(Connection)connections.elementAt(0);
connections.removeElementAt(0);
}
return conn;
}
public synchronized void putConnection(Connection conn)//返回可用连接
{
connections.addElement(conn);
notifyAll();
}
public synchronized void removeAllConnections()//清空connections矢量
{
try{
if(connections ==null)
return;
int sz=connections.size();
for(int i=0;i <sz;i++)
{
Connection conn =(Connection)connections.elementAt(i);
conn.close();
}
connections.removeAllElements();
connections=null;
}catch(SQLException sqle){}
}
}
[解决办法]
前些天发了个数据库连接总结的 希望大家补充下 2天没人看 悲哀呀
[解决办法]
现在的服务器基本上都支持管理数据库连接池的功能,你只要在服务器中配置好你的数据源后,在程序里lookup就可以使用了,你写的那是你自己实现的,如果自定义的连接池,好想有个proxool的东东。它要你自己编程实现自己的连接池管理功能,类似你写的那东西。
不同的服务器配置不同,给个tomcat的例子(也可以在tomat的图形界面配置,这里直接改配置文件):
在server.conf文件中,找到你的应用,加上如下代码:
<Context path= "/desconn " reloadable= "true " docBase= "D:\tomcatApp\TestApp\WebRoot " workDir= "D:\tomcatApp\TestApp\WebRoot\WEB-INF\Work ">
<!-- 配置数据源,JNDI名字为 “jdbc/testDS” -->
<Resource auth= "Container " description= "test MS Connection " name= "jdbc/testDS " type= "javax.sql.DataSource "/>
<ResourceParams name= "jdbc/testDS ">
<parameter>
<name> factory </name>
<value> org.apache.commons.dbcp.BasicDataSourceFactory </value>
</parameter>
<parameter>
<name> maxActive </name>
<value> 50 </value>
</parameter>
<parameter>
<name> maxWait </name>
<value> 1000 </value>
</parameter>
<parameter>
<name> username </name>
<value> sa </value>
</parameter>
<parameter>
<name> password </name>
<value> sa </value>
</parameter>
<parameter>
<name> url </name>
<value> jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=testDB </value>
</parameter>
<parameter>
<name> driverClassName </name>
<value> com.microsoft.jdbc.sqlserver.SQLServerDriver </value>
</parameter>
<parameter>
<name> maxIdle </name>
<value> 30 </value>
</parameter>
</ResourceParams>
</Context>
程序使用配置的数据源:
<%@ page language= "java " pageEncoding= "UTF-8 "%>
<%@ page import= "java.util.* " %>
<%@ page import= "java.sql.* " %>
<%@ page import= "javax.sql.* " %>
<%@ page import= "javax.naming.* " %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+ ":// "+request.getServerName()+ ": "+request.getServerPort()+path+ "/ ";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN ">
<html>
<head>
<base href= " <%=basePath%> ">
<title> My JSP 'TestDesConn.jsp ' starting page </title>
<meta http-equiv= "pragma " content= "no-cache ">
<meta http-equiv= "cache-control " content= "no-cache ">
<meta http-equiv= "expires " content= "0 ">
<meta http-equiv= "keywords " content= "keyword1,keyword2,keyword3 ">
<meta http-equiv= "description " content= "This is my page ">
<!--
<link rel= "stylesheet " type= "text/css " href= "styles.css ">
-->
</head>
<body>
测试tomcat数据库连接池br>
<%
int i = 0 ;
try{
Context ctx = null;
DataSource ds = null;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String JNDI = "java:comp/env/jdbc/testDS " ; //tomcat中配置的jdbi名字
ctx = new InitialContext();
ds = ( DataSource ) ctx.lookup(JNDI); //通过jndi取得一个连接
conn = ds.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery( "select * from testTable ");
while (rs.next()) {
i++;
}
}catch (Exception e) {
e.printStackTrace();
}
System.out.println( "一共有 " + i + " 记录!);
%>
</body>
</html>
[解决办法]
apache dbcp
[解决办法]
yanhuaxie 的已经很好了,你可以根据自己的需要在加工修改下就OK了
------解决方案--------------------
去Tomcat的JNDI Resources 里设置 数据连接池
[解决办法]
http://blog.csdn.net/qianlei0007/archive/2007/02/19/1511927.aspx
去看看。。
[解决办法]
找本书仔细看下问题不大
ORM的就写配制文件,别的就自己写代码
[解决办法]
弱弱的问一下,ORM是什么意思啊
[解决办法]
Object Relational Mapping
一般是做持久层的实现
[解决办法]
传说中的mark.
[解决办法]
怎么那么多人要:
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(makeNewConnection());
}
}
public synchronized Connection getConnection()
throws SQLException {
if (!availableConnections.isEmpty()) {
Connection existingConnection =
(Connection)availableConnections.lastElement();
int lastIndex = availableConnections.size() - 1;
availableConnections.removeElementAt(lastIndex);
// If connection on available list is closed (e.g.,
// it timed out), then remove it from available list
// and repeat the process of obtaining a connection.
// Also wake up threads that were waiting for a
// connection because maxConnection limit was reached.
if (existingConnection.isClosed()) {
notifyAll(); // Freed up a spot for anybody waiting
return(getConnection());
} else {
busyConnections.addElement(existingConnection);
return(existingConnection);
}
} else {
// Three possible cases:
// 1) You haven 't reached maxConnections limit. So
// establish one in the background if there isn 't
// already one pending, then wait for
// the next available connection (whether or not
// it was the newly established one).
// 2) You reached maxConnections limit and waitIfBusy
// flag is false. Throw SQLException in such a case.
// 3) You reached maxConnections limit and waitIfBusy
// flag is true. Then do the same thing as in second
// part of step 1: wait for next available connection.
if ((totalConnections() < maxConnections) &&
!connectionPending) {
makeBackgroundConnection();
} else if (!waitIfBusy) {
throw new SQLException( "Connection limit reached ");
}
// Wait for either a new connection to be established
// (if you called makeBackgroundConnection) or for
// an existing connection to be freed up.
try {
wait();
} catch(InterruptedException ie) {}
// Someone freed up a connection, so try again.
return(getConnection());
}
}
// You can 't just make a new connection in the foreground
// when none are available, since this can take several
// seconds with a slow network connection. Instead,
// start a thread that establishes a new connection,
// then wait. You get woken up either when the new connection
// is established or if someone finishes with an existing
// connection.
private void makeBackgroundConnection() {
connectionPending = true;
try {
Thread connectThread = new Thread(this);
connectThread.start();
} catch(OutOfMemoryError oome) {
// Give up on new connection
}
}
public void run() {
try {
Connection connection = makeNewConnection();
synchronized(this) {
availableConnections.addElement(connection);
connectionPending = false;
notifyAll();
}
} catch(Exception e) { // SQLException or OutOfMemory
// Give up on new connection and wait for existing one
// to free up.
}
}
// This explicitly makes a new connection. Called in
// the foreground when initializing the ConnectionPool,
// and called in the background when running.
private Connection makeNewConnection()
throws SQLException {
try {
// Load database driver if not already loaded
Class.forName(driver);
// Establish network connection to database
Connection connection =
DriverManager.getConnection(url, username, password);
return(connection);
} catch(ClassNotFoundException cnfe) {
// Simplify try/catch blocks of people using this by
// throwing only one exception type.
throw new SQLException( "Can 't find class for driver: " +
driver);
}
}
public synchronized void free(Connection connection) {
busyConnections.removeElement(connection);
availableConnections.addElement(connection);
// Wake up threads that are waiting for a connection
notifyAll();
}
public synchronized int totalConnections() {
return(availableConnections.size() +
busyConnections.size());
}
/** Close all the connections. Use with caution:
* be sure no connections are in use before
* calling. Note that you are not <I> required </I> to
* call this when done with a ConnectionPool, since
* connections are guaranteed to be closed when
* garbage collected. But this method gives more control
* regarding when the connections are closed.
*/
public synchronized void closeAllConnections() {
closeConnections(availableConnections);
availableConnections = new Vector();
closeConnections(busyConnections);
busyConnections = new Vector();
}
private void closeConnections(Vector connections) {
try {
for(int i=0; i <connections.size(); i++) {
Connection connection =
(Connection)connections.elementAt(i);
if (!connection.isClosed()) {
connection.close();
}
}
} catch(SQLException sqle) {
// Ignore errors; garbage collect anyhow
}
}
public synchronized String toString() {
String info =
"ConnectionPool( " + url + ", " + username + ") " +
", available= " + availableConnections.size() +
", busy= " + busyConnections.size() +
", max= " + maxConnections;
return(info);
}
}
2.单键类
package yourapplication.utility.db;
import java.sql.SQLException;
public class BookConnPool extends ConnectionPool {
private static BookConnPool pool = null;
private BookConnPool(String driver, String url, String username,
String password, int initialConnections, int maxConnections,
boolean waitIfBusy) throws SQLException {
super(driver, url, username,
password, initialConnections, maxConnections,
waitIfBusy); // Call parent constructor
}
public static synchronized BookConnPool getInstance() throws SQLException {
if (pool == null) {
//这里从配置文件中读取相应的参数
String driver = " "; //这里填你的数据库驱动
String url = " ";//这里填db相应的url包含端口和服务名
String usrname = " ";
String passwd = " ";
pool = new BookConnPool(driver, url,usrname, passwd, 100,1000,true);
}
return (pool);
}
}