今天写了些测试,留下一个简易的连接池,其实用框架好用,但是相对于小型的开发速度来说 javabean+servlet速度似乎更快,这里留点记录,以备日后心血来潮完善把。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Vector;
public class DBManager {
private Connection conn = null;
private PreparedStatement pstmt = null;
private Statement stmt = null;
private ResultSet rs = null;
private static Vector dsprool = new Vector
();
/**
*
*/
private DBManager() {
}
public static DBManager _INSTANCE = new DBManager();
public static DBManager getDBManager() {
return _INSTANCE;
}
public Connection getConnection() {
// return getPoolConn();
try {
Class.forName(Config.getConfig().getProperty("DBDRIVER"));
} catch (ClassNotFoundException e) {
System.out.println("加载驱动失败");
}
try {
conn = DriverManager.getConnection(Config.getConfig().getProperty(
"DBURL"), Config.getConfig().getProperty("DBUSER"), Config
.getConfig().getProperty("DBPASSWORD"));
} catch (SQLException e) {
System.out.println("数据库用户名密码不匹配");
}
// System.out.println("获取连接");
return conn;
}
/**
* 创建连接池
*/
public void CreateDS() {
for (int i = 0; i < 50; i++) {
dsprool.add(getConnection());
}
System.out.println("create ds over……");
}
/**
* 获取连接池链接
*
* @return
*/
public Connection getDSConn() {
if (dsprool.isEmpty()) {
try {
Thread.sleep(1000 * 2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getDSConn();
} else {
return (Connection) dsprool.remove(0);
}
return null;
}
/**
* 链接回池
*
* @param conn
*/
public void BackConn(Connection conn) {
if (conn != null) {
dsprool.add(conn);
}
}
/**
* 销毁连接池
*/
public void DestoryDS() {
Iterator it = dsprool.iterator();
while (it.hasNext()) {
Connection conns = (Connection) it.next();
if (conns != null) {
try {
conns.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
你可以在项目启动的时候创建连接池,来初始化。这个很建议,建议修改测试使用。