JDBC连接池一 自定义连接池
package com.mozq.jdbc; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; /** * 使用Properties类,从配置文件获取配置信息。实现JDBCUtils工具类 * * @author jie * */ public class JDBCUtils_V2 { // 1.准备配置信息 public static String dirverClass; public static String url; public static String user; public static String password; static { ClassLoader classLoader = JDBCUtils_V2.class.getClassLoader(); InputStream inStream = classLoader.getResourceAsStream("db.properties"); Properties properties = new Properties(); try { properties.load(inStream); dirverClass = properties.getProperty("dirverClass"); url = properties.getProperty("url"); user = properties.getProperty("user"); password = properties.getProperty("password"); Class.forName(dirverClass); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 获取连接 * * @throws ClassNotFoundException */ public static Connection getConnection() { // 2.加载驱动,获得链接 Connection connection = null; try { connection = DriverManager.getConnection(url, user, password); }catch (SQLException e) { e.printStackTrace(); } return connection; } /** * 释放资源,注意资源的释放顺序 */ public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) { if(rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
package com.mozq.jdbc; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; /** * 装饰者设计模式:需要增强接口实现类的接口方法。创建实现接口的一个装饰类。 * 实例:增强Connection实现类的close()方法 * 装饰类的设计步骤: * 1.实现接口 * 2.提供含有接口类型参数的构造器 * 3.提供接口类型成员变量 * 4.增强需要的方法 * 5.调用接口类型变量,实现不需要增强的方法 * @author jie * */ public class MyConnection implements Connection { //1.定义接口变量 private Connection conn; private List<Connection> pool; //2.定义接口变量为参数的构造器 public MyConnection(Connection conn , List<Connection> pool){ this.conn = conn; this.pool = pool; } //3.增强需要的方法 @Override public void close() throws SQLException { pool.add(conn); System.out.println("将连接放回连接池"); } //4.调用接口变量,实现不需要增强的方法 @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return conn.prepareStatement(sql); } @Override public <T> T unwrap(Class<T> iface) throws SQLException { // TODO Auto-generated method stub return null; } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { // TODO Auto-generated method stub return false; } @Override public Statement createStatement() throws SQLException { // TODO Auto-generated method stub return null; } @Override public CallableStatement prepareCall(String sql) throws SQLException { // TODO Auto-generated method stub return null; } @Override public String nativeSQL(String sql) throws SQLException { // TODO Auto-generated method stub return null; } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { // TODO Auto-generated method stub } @Override public boolean getAutoCommit() throws SQLException { // TODO Auto-generated method stub return false; } @Override public void commit() throws SQLException { // TODO Auto-generated method stub } @Override public void rollback() throws SQLException { // TODO Auto-generated method stub } @Override public boolean isClosed() throws SQLException { // TODO Auto-generated method stub return false; } @Override public DatabaseMetaData getMetaData() throws SQLException { // TODO Auto-generated method stub return null; } @Override public void setReadOnly(boolean readOnly) throws SQLException { // TODO Auto-generated method stub } @Override public boolean isReadOnly() throws SQLException { // TODO Auto-generated method stub return false; } @Override public void setCatalog(String catalog) throws SQLException { // TODO Auto-generated method stub } @Override public String getCatalog() throws SQLException { // TODO Auto-generated method stub return null; } @Override public void setTransactionIsolation(int level) throws SQLException { // TODO Auto-generated method stub } @Override public int getTransactionIsolation() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public SQLWarning getWarnings() throws SQLException { // TODO Auto-generated method stub return null; } @Override public void clearWarnings() throws SQLException { // TODO Auto-generated method stub } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { // TODO Auto-generated method stub return null; } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { // TODO Auto-generated method stub return null; } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { // TODO Auto-generated method stub return null; } @Override public void setTypeMap(Map<String, Class<?>> map) throws SQLException { // TODO Auto-generated method stub } @Override public void setHoldability(int holdability) throws SQLException { // TODO Auto-generated method stub } @Override public int getHoldability() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public Savepoint setSavepoint() throws SQLException { // TODO Auto-generated method stub return null; } @Override public Savepoint setSavepoint(String name) throws SQLException { // TODO Auto-generated method stub return null; } @Override public void rollback(Savepoint savepoint) throws SQLException { // TODO Auto-generated method stub } @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { // TODO Auto-generated method stub } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { // TODO Auto-generated method stub return null; } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { // TODO Auto-generated method stub return null; } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { // TODO Auto-generated method stub return null; } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { // TODO Auto-generated method stub return null; } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { // TODO Auto-generated method stub return null; } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Clob createClob() throws SQLException { // TODO Auto-generated method stub return null; } @Override public Blob createBlob() throws SQLException { // TODO Auto-generated method stub return null; } @Override public NClob createNClob() throws SQLException { // TODO Auto-generated method stub return null; } @Override public SQLXML createSQLXML() throws SQLException { // TODO Auto-generated method stub return null; } @Override public boolean isValid(int timeout) throws SQLException { // TODO Auto-generated method stub return false; } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { // TODO Auto-generated method stub } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { // TODO Auto-generated method stub } @Override public String getClientInfo(String name) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Properties getClientInfo() throws SQLException { // TODO Auto-generated method stub return null; } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { // TODO Auto-generated method stub return null; } @Override public void setSchema(String schema) throws SQLException { // TODO Auto-generated method stub } @Override public String getSchema() throws SQLException { // TODO Auto-generated method stub return null; } @Override public void abort(Executor executor) throws SQLException { // TODO Auto-generated method stub } @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { // TODO Auto-generated method stub } @Override public int getNetworkTimeout() throws SQLException { // TODO Auto-generated method stub return 0; } }
package com.mozq.jdbc; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.LinkedList; import java.util.logging.Logger; import javax.sql.DataSource; public class MyDataSourceMyConn implements DataSource { // 准备一个池子保存连接 private static LinkedList<Connection> pool = new LinkedList<Connection>(); // 从配置文件加载参数 private static int init = 5; static { // 初始化池子 for (int i = 0; i < init; ++i) { Connection connection = JDBCUtils_V2.getConnection(); //增强Connection实现类 MyConnection myConnection = new MyConnection(connection, pool); pool.add(myConnection); } } /** * 覆盖获取连接的方法 */ @Override public Connection getConnection() throws SQLException { // 获取连接前先判断 if (pool.size() == 0) { //如果没有连接,创建一些 for (int i = 0; i < init; ++i) { Connection connection = JDBCUtils_V2.getConnection(); //增强Connection实现类 MyConnection myConnection = new MyConnection(connection, pool); pool.add(myConnection); } } //从池子里获取连接返回 return pool.remove(); } @Override public PrintWriter getLogWriter() throws SQLException { // TODO Auto-generated method stub return null; } @Override public void setLogWriter(PrintWriter out) throws SQLException { // TODO Auto-generated method stub } @Override public void setLoginTimeout(int seconds) throws SQLException { // TODO Auto-generated method stub } @Override public int getLoginTimeout() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { // TODO Auto-generated method stub return null; } @Override public <T> T unwrap(Class<T> iface) throws SQLException { // TODO Auto-generated method stub return null; } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { // TODO Auto-generated method stub return false; } @Override public Connection getConnection(String username, String password) throws SQLException { // TODO Auto-generated method stub return null; } }
package com.mozq.jdbc.test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.sql.DataSource; import org.junit.Test; import com.mozq.jdbc.JDBCUtils_V2; import com.mozq.jdbc.MyDataSourceMyConn; public class MyDataSourceMyConnTest { @Test public void insert() { // 准备参数 String user = "刘备"; String password = "123"; Connection conn = null; PreparedStatement pstmt = null; DataSource myDataSource = new MyDataSourceMyConn(); try { // 获取链接 conn = myDataSource.getConnection(); // 获取语句执行对象 String sql = "insert into t_user (name, password) values(?, ?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, user); pstmt.setString(2, password); // 结果处理 int row = pstmt.executeUpdate(); if (row > 0) { System.out.println("插入用户成功"); } else { System.out.println("插入用户失败"); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils_V2.release(conn, pstmt, null);; } } }