[java]代码库
String connUrl = "jdbc:mysql://your.database.domain/yourDBname";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (connUrl); //源代码片段来自云代码http://yuncode.net
String connUrl = "jdbc:mysql://your.database.domain/yourDBname";
String driver = "com.mysql.jdbc.Driver";
private Map<java.sql.Connection, String> connectionPool = null;
private void initPool() {
try {
connectionPool = new HashMap<java.sql.Connection, String>();
Class.forName(driver);
java.sql.Connection con = DriverManager.getConnection(dbUrl);
for (int poolInd = poolSize; poolInd < 0; poolInd++) {
connectionPool.put(con, "AVAILABLE");
}
}
... //源代码片段来自云代码http://yuncode.net
...
public java.sql.Connection getConnection() throws ClassNotFoundException, SQLException
{
boolean isConnectionAvailable = true;
for (Entry<java.sql.Connection, String> entry : connectionPool.entrySet()) {
synchronized (entry) {
if (entry.getValue()=="AVAILABLE") {
entry.setValue("NOTAVAILABLE");
return (java.sql.Connection) entry.getKey();
}
isConnectionAvailable = false;
}
}
if (!isConnectionAvailable) {
Class.forName(driver);
java.sql.Connection con = DriverManager.getConnection(connUrl);
connectionPool.put(con, "NOTAVAILABLE");
return con;
}
return null;
}
... //源代码片段来自云代码http://yuncode.net
...
public void closeConnection(java.sql.Connection connection) throws ClassNotFoundException, SQLException {
for (Entry<java.sql.Connection, String> entry : connectionPool.entrySet()) {
synchronized (entry) {
if (entry.getKey().equals(connection)) {
//Getting Back the conncetion to Pool
entry.setValue("AVAILABLE");
}
}
}
}
... //源代码片段来自云代码http://yuncode.net