代碼:import java.io.FileInputStream;import java.io.FileNotFoundException;
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.LinkedList; import java.util.Properties; import org.slf4j.Logger; public class ConnPool { // 使用LinkedList集合存放數據庫連接 private static LinkedList<Connection> connPool = new LinkedList<Connection>(); // 在靜態代碼塊中加載配置文件 static {
//如果以jar包運行,此處會報找不到這個文件的異常,解決方案如下。 String path = ConnPool.class.getClassLoader().getResource("db.properties").getPath();//解決方案需要注釋這行代碼
//InputStream in = PropertiesUtil.class.getClassLoader.getResourceAsStream("db.properties");//開啟這行代碼解決以上問題
FileInputStream in;//開啟以上解決方案需要注釋調這行代碼 try { in = new FileInputStream(path);//開啟以上解決方案需要注釋這行代碼 Properties prop = new Properties(); prop.load(in); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String user = prop.getProperty("user"); String password = prop.getProperty("password"); // 數據庫連接池的初始化連接數的大小 int InitSize = Integer.parseInt(prop.getProperty("InitSize")); // 加載驅動 Class.forName(driver); for (int i = 0; i < InitSize; i++) { Connection conn = DriverManager.getConnection(url, user, password); // 將創建的連接添加的list中 System.out.println("初始化數據庫連接池,創建第 " + (i + 1) + " 個連接,添加到池中"); connPool.add(conn); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } /*獲取數據庫連接*/ public Connection getConnection() throws SQLException { if(connPool.size() > 0){ //從集合中獲取一個連接 final Connection conn = connPool.removeFirst(); //返回Connection的代理對象 return (Connection) Proxy.newProxyInstance(ConnPool.class.getClassLoader(), conn.getClass().getInterfaces(), new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(!"close".equals(method.getName())){ return method.invoke(conn, args); }else{ connPool.add(conn); System.out.println("關閉當前連接,把連接還給連接池........."); System.out.println("池中連接數為 " + connPool.size()); return null; } } }); }else{ throw new RuntimeException("數據庫繁忙,稍后再試............"); } } public PrintWriter getLogWriter() throws SQLException { return null; } public void setLogWriter(PrintWriter out) throws SQLException { } public void setLoginTimeout(int seconds) throws SQLException { } public int getLoginTimeout() throws SQLException { return 0; } public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } public Object unwrap(Class iface) throws SQLException { return null; } public boolean isWrapperFor(Class iface) throws SQLException { return false; } public Connection getConnection(String username, String password) throws SQLException { return null; } }
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JdbcUtil { //數據庫連接池 private static ConnPool connPool = new ConnPool(); /** * 從池中獲取一個連接 * @return * @throws SQLException */ public static Connection getConnection() throws SQLException{ return connPool.getConnection(); } /** * 關閉連接 * @param conn * @param st * @param rs * @throws SQLException */ public static void CloseConnection(Connection conn, Statement st, ResultSet rs) throws SQLException{ // 關閉存儲查詢結果的ResultSet對象 if(rs != null){ rs.close(); } //關閉Statement對象 if(st != null){ st.close(); } //關閉連接 if(conn != null){ conn.close(); } } }
db.properties
driver = com.mysql.cj.jdbc.Driver url = jdbc:mysql://localhost:3306/數據庫名?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=TRUE user = root password = root InitSize = 15
調用如下:
JdbcUtil jdbcUtil = new JdbcUtil();
String sql = "要寫的SQL語句"; Connection connection = null; Statement statement = null; ResultSet resultSet = null;
try{ connection = jdbcUtil.getConnection(); statement = connection.createStatement(); resultSet = statement.executeQuery(sql); while (resultSet.next()) { String id= resultSet.getString("id"); if (id!= null) {
//可以在這里寫業務邏輯
}
}
} catch (Exception e) { logger.error("數據獲取失敗", e); msg = createResultJson(1, "數據獲取失敗!"); } finally { try { jdbcUtil.CloseConnection(connection, statement, resultSet);//最后記得關閉流,不然會報創建連接過多的異常 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }