嗨,我想創建數據庫連接池。下面的方法是正確的。數據庫連接池
public Connection getMySQLConnection(){
Connection conn = null;
String url = "jdbc:mysql://" + Config.getInstance().getProperty("DB_SERVER_HOST") + ":" + Config.getInstance().getProperty("DB_SERVER_PORT") + "/" + Config.getInstance().getProperty("DB_NAME");
try {
poolConn = new DbPool("com.mysql.jdbc.Driver", url, Config.getInstance().getProperty("DB_USERNAME"), Config.getInstance().getProperty("DB_PASSWORD"));
} catch (SQLException e) {
LOGGER.error("error while creating the connection pool : "+e);
}
try {
conn = poolConn.getConnection();
} catch (SQLException e) {
LOGGER.error("Error while getting connection from db pool"+e);
}
return conn;
}
這是我的自定義DbPool類的構造函數。在上面的代碼中,我創建了這個類的對象。
public DbPool(String classname, String url, String username,
String password) throws java.sql.SQLException {
try {
Class.forName(classname).newInstance();
} catch (Exception e) { // Catch any exception from JDBC driver failure
LOGGER.error("Failed to load JDBC driver: "+classname
+", Exception: "+e);
}
maxConnections = defaultMaxConnections;
timeout = defaultTimeout;
if (DEBUG) {
maxConnections = debugDefaultMaxConnections;
timeout = debugDefaultTimeout;
}
totalConnections = 0;
freeList = new java.util.LinkedList<DBPoolConnection>();
busy = new java.util.HashMap<Connection, DBPoolConnection>();
this.url = url;
connectionProperties = new java.util.Properties();
if (username == null) LOGGER.info("ERROR: Null JDBC username");
else connectionProperties.setProperty("user",username);
if (password == null) LOGGER.info("ERROR: Null JDBC password");
else connectionProperties.setProperty("password",password);
}
什麼是'poolConn'? –
爲什麼不使用ORM框架並讓它管理連接池?或使用已有的 - (BoneCP)http://jolbox.com/例如 – hovanessyan
爲什麼不簡單試一試,看看它是否有效?請更具體地說明您的實際問題(如果有的話...)。 – dirkk