DB. java
Package wkx. db;
Import java. SQL. Connection;
Import java. SQL. ResultSet;
Import java. SQL. SQLException;
Import java. SQL. Statement;
Public class DB {
Public static int executeUpdate (String SQL ){
Int ans = 0;
Connection conn = DB. getConn ();
Statement stmt = DB. getStmt (conn );
Try {
Ans = stmt.exe cuteUpdate (SQL );
} Catch (SQLException e ){
E. printStackTrace ();
} Finally {
DB. close (stmt );
DB. close (conn );
}
Return ans;
}
Public static Connection getConn (){
Return ConnPool. getConn ();
}
Public static Statement getStmt (Connection conn ){
Statement stmt = null;
Try {
Stmt = conn. createStatement ();
} Catch (SQLException e ){
E. printStackTrace ();
}
Return stmt;
}
Public static ResultSet executeQuery (Statement stmt, String SQL ){
// System. out. println ("QUERY:" + SQL );
ResultSet rs = null;
Try {
Rs = stmt.exe cuteQuery (SQL );
} Catch (SQLException e ){
E. printStackTrace ();
}
Return rs;
}
Public static void close (Connection conn ){
ConnPool. close (conn );
}
Public static void close (Statement stmt ){
Try {
If (stmt! = Null ){
Stmt. close ();
}
} Catch (SQLException e ){
E. printStackTrace ();
}
Stmt = null;
}
Public static void close (ResultSet rs ){
Try {
If (rs! = Null ){
Rs. close ();
}
} Catch (SQLException e ){
E. printStackTrace ();
}
Rs = null;
}
Public static void closeAll (Connection conn, Statement stmt ){
DB. close (conn );
DB. close (stmt );
}
Public static void closeAll (Connection conn, Statement stmt, ResultSet rs ){
DB. close (conn );
DB. close (stmt );
DB. close (rs );
}
}
ConnPool. java
[Java]
Package wkx. db;
Import java. SQL. Connection;
Import java. SQL. DriverManager;
Import java. SQL. SQLException;
Import java. util. Collections list;
Public class ConnPool {
Public static final int MAX_CONN_NUM = 10;
Private static Nation List <Connection> conns = null;
Private static int connNum = 0;
Static {
Conns = new consumer list <Connection> ();
}
Private ConnPool (){
}
Public static Connection getConn (){
Connection conn = null;
If (conns. size () = 0 ){
Try {
Class. forName ("com. mysql. jdbc. Driver ");
Conn = DriverManager. getConnection (
"Jdbc: mysql: // localhost: 3306/project", "root", "root ");
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
} Catch (SQLException e ){
E. printStackTrace ();
}
ConnNum ++;
} Else {
Conn = conns. pop ();
}
/**
*
*/
ConnPool. printStatus ();
Return conn;
}
Public static void close (Connection conn ){
If (connNum> ConnPool. MAX_CONN_NUM ){
Try {
If (conn! = Null ){
Conn. close ();
}
} Catch (SQLException e ){
E. printStackTrace ();
}
Conn = null;
ConnNum --;
} Else {
Conns. push (conn );
}
ConnPool. printStatus ();
}
Public static void printStatus (){
System. out. println ("idle connections:" + conns. size () + "Total connections:" + connNum + "used connections:" + (connNum-conns.size ()));
}
}