簡単なJDBCデータベース接続プール、リソースプロファイルの読み取り!
11254 ワード
JDBCデータベース接続プールの簡単な実現、リソースプロファイルの読み取り、あまり完備していないので、アドバイスをお願いします.のリソースファイルconn.properties データベースに接続するツールクラスDbCon.java
conn.driver=com.mysql.jdbc.Driver
conn.url=jdbc:mysql://localhost:3306/test
conn.user=root
conn.password=xxm
conn.minCon=30
conn.maxCon=100
package com.xxm.utils;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Vector;
/**
*
* @author D-xxm
*/
public class DbCon {
private static String className = null;
private static String url = null;
private static String user = null;
private static String password = null;
private static int minCon = 3; //
private static List<Connection> listCon = new Vector<Connection>(); //
/**
*
*/
static {
loadProperties();
try {
for (int i = 0; i < minCon; i++) {
listCon.add(getCon());
}
} catch (SQLException e) {
System.out.println("--------------- !---------------");
e.printStackTrace();
}
System.out.println("--------------- "+listCon.size()+" !---------------");
}
/**
* 、
* @throws IOException
* @throws ClassNotFoundException
*/
private static void loadProperties() {
ResourceBundle rb;
try {
rb = ResourceBundle.getBundle("conn");
className = rb.getString("conn.driver");
url = rb.getString("conn.url");
user = rb.getString("conn.user");
password = rb.getString("conn.password");
String smin = rb.getString("conn.minCon");
if ((smin != null) && (!("".equals(smin.trim()))))
minCon = Integer.valueOf(smin).intValue();
Class.forName(className);
} catch (Exception e) {
System.out.println("--------------- !--------------");
className = "com.mysql.jdbc.Driver";
url = "jdbc:mysql://localhost:3306/demo";
user = "root";
password = "xxm";
try {
Class.forName(className);
} catch (Exception e2) {
System.out.println("--------------- !--------------");
e2.printStackTrace();
}
}
}
/**
* 。。。
* @return
* @throws SQLException
*/
private static Connection getCon() throws SQLException {
System.out.println("--------------- !---------------");
if ((className == null) || (url == null) || (password==null))
loadProperties();
return DriverManager.getConnection(url, user, password);
}
/**
* 、 、
* @return
* @throws SQLException*/
public static Connection getConnection() throws SQLException {
if ((listCon != null) && (listCon.size() > 0))
return listCon.remove(listCon.size() - 1);
return getCon();
}
/**
* 、 、
* @param con
* @throws SQLException
*/
public static void closeConnection(Connection conn) throws Exception {
if ((conn != null) && (!(conn.isClosed())))
if ((listCon != null) && (listCon.size() < minCon))
listCon.add(conn);
else
conn.close();
}
/**
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
for (int i = 0; i < 40; ++i) {
Connection conn = getConnection();
System.out.println(conn);
}
System.out.println(listCon.size());
}
}