import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DataSourceDemo { public static void main(String[] args) throws SQLException { //1、创建连接池对象 JdbcDemo jd = new JdbcDemo(); System.out.println("使用之前的连接池数量:" + jd.getSize()); //2、通过连接池对象获取连接对象 Connection con = jd.getConnection(); //3、预编译查询语句 String sql = "select * from users"; PreparedStatement ps = con.prepareStatement(sql); //4、执行sql,获取结果集 ResultSet rs = ps.executeQuery(); //5、处理结果集 while (rs.next()) { System.out.println(rs.getInt("id") + "\t" + rs.getString("name") + "\t" + rs.getInt("age")); } //6、释放资源 rs.close(); ps.close(); con.close(); System.out.println("使用之后的连接池数量:" + jd.getSize()); } }
import javax.sql.DataSource; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; /** * 自定义数据库连接池 */ public class JdbcDemo implements DataSource { //1、准备容器,用于保存连接对象。因为list是线程不安全的,使用Collections.synchronizedList变成线程安全的对象 private static List<Connection> pool = Collections.synchronizedList(new ArrayList<>()); //2、定义静态代码块,通过工具类生成10个连接池对象 static { for (int i = 0; i < 10; i++) { Connection connection = JDBCUtils.getConnection(); pool.add(connection); } } //3、获取一个连接对象 @Override public Connection getConnection() throws SQLException { //判断连接池有没有连接对象,如果有,删除0索引上的对象,获取这个从集合中删除的连接对象,这样就可以获取到一个连接对象 if (pool.size() > 0) { Connection con = pool.remove(0); //方式1、通过自定义对象对原来的对象进行包装(装饰设计模式) //MyConnection mc = new MyConnection(con,pool); //返回自定义的连接对象 //return mc; //方式2、使用继承的适配器类 MyConnection1 mc1 = new MyConnection1(con,pool); return mc1; } else { throw new RuntimeException("连接已用完"); } } //4、定义getSize方法,获取连接池容器大小,通过该方法可以获取连接池剩余数量 public int getSize(){ return pool.size(); } @Override public Connection getConnection(String username, String password) throws SQLException { return null; } @Override public <T> T unwrap(Class<T> iface) throws SQLException { return null; } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; } @Override public PrintWriter getLogWriter() throws SQLException { return null; } @Override public void setLogWriter(PrintWriter out) throws SQLException { } @Override public void setLoginTimeout(int seconds) throws SQLException { } @Override public int getLoginTimeout() throws SQLException { return 0; } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } }
import java.io.InputStream; import java.sql.*; import java.util.Properties; /** * JDBC工具类 */ public class JDBCUtils { //1、构造方法私有化,工具类方法应该使用静态方法 private JDBCUtils() { } //2、声明所需的配置变量 private static String driverClass; //注册驱动的信息 private static String url; //MySQL的地址 private static String username; //MySQL用户名 private static String password; //MySQL密码 private static Connection con; //3、提供静态代码块,读取配置文件的信息,注册驱动 static { try { //读取配置文件的信息为变量赋值(配置文件保存在src下,通过类加载器方式获取配置文件) InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("config.properties"); Properties prop = new Properties(); prop.load(is); //赋值 driverClass = prop.getProperty("driverClass"); url = prop.getProperty("url"); username = prop.getProperty("username"); password = prop.getProperty("password"); //注册驱动 Class.forName(driverClass); } catch (Exception e) { throw new RuntimeException(e); } } //4、提供获取数据库连接方法 public static Connection getConnection() { try { con = DriverManager.getConnection(url, username, password); } catch (SQLException e) { throw new RuntimeException(e); } return con; } //5、提供释放资源方法 public static void close(Connection con, Statement stst, ResultSet rs) { if (con != null) { try { con.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if (stst != null) { try { stst.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } }
/** * 步骤 * 1、定义一个类继承适配器类 * 2、定义连接池对象和连接对象 * 3、定义有参构造方法为连接池对象和连接对象赋值 * 4、重写close方法,完成归还连接 */ //1、继承适配器类 public class MyConnection1 extends MyAdapter { //2、定义连接池对象和连接对象 private Connection con; private List<Connection> list; //3、定义有参构造方法为连接池对象和连接对象赋值 public MyConnection1(Connection con, List<Connection> list) { super(con); this.con = con; this.list = list; } //4、重写close方法,将连接对象归还到连接池 @Override public void close() throws SQLException { list.add(con); } }
/** * 适配器类(中间类,一般都是抽象类,可以有普通方法,也可以有抽象方法,还可以有构造方法) * 实现Connection接口,重写除了close之外的方法 */ public abstract class MyAdapter implements Connection { //定义连接对象 private Connection con; //定义有参构造方法为连接对象赋值 public MyAdapter(Connection con) { this.con = con; } //5、下面其他的重写方法还是调用原来的方法,功能不变 @Override public Statement createStatement() throws SQLException { return con.createStatement(); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return con.prepareStatement(sql); } @Override public CallableStatement prepareCall(String sql) throws SQLException { return con.prepareCall(sql); } @Override public String nativeSQL(String sql) throws SQLException { return con.nativeSQL(sql); } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { con.setAutoCommit(autoCommit); } @Override public boolean getAutoCommit() throws SQLException { return con.getAutoCommit(); } @Override public void commit() throws SQLException { con.commit(); } @Override public void rollback() throws SQLException { con.rollback(); } @Override public boolean isClosed() throws SQLException { return con.isClosed(); } @Override public DatabaseMetaData getMetaData() throws SQLException { return con.getMetaData(); } @Override public void setReadOnly(boolean readOnly) throws SQLException { con.setReadOnly(readOnly); } @Override public boolean isReadOnly() throws SQLException { return con.isReadOnly(); } @Override public void setCatalog(String catalog) throws SQLException { con.setCatalog(catalog); } @Override public String getCatalog() throws SQLException { return con.getCatalog(); } @Override public void setTransactionIsolation(int level) throws SQLException { con.setTransactionIsolation(level); } @Override public int getTransactionIsolation() throws SQLException { return con.getTransactionIsolation(); } @Override public SQLWarning getWarnings() throws SQLException { return con.getWarnings(); } @Override public void clearWarnings() throws SQLException { con.clearWarnings(); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return con.createStatement(resultSetType, resultSetConcurrency); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return con.prepareStatement(sql, resultSetType, resultSetConcurrency); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return con.prepareCall(sql, resultSetType, resultSetConcurrency); } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { return con.getTypeMap(); } @Override public void setTypeMap(Map<String, Class<?>> map) throws SQLException { con.setTypeMap(map); } @Override public void setHoldability(int holdability) throws SQLException { con.setHoldability(holdability); } @Override public int getHoldability() throws SQLException { return con.getHoldability(); } @Override public Savepoint setSavepoint() throws SQLException { return con.setSavepoint(); } @Override public Savepoint setSavepoint(String name) throws SQLException { return con.setSavepoint(name); } @Override public void rollback(Savepoint savepoint) throws SQLException { con.rollback(); } @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { con.releaseSavepoint(savepoint); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return con.createStatement(resultSetType, resultSetConcurrency); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return con.prepareStatement(sql, resultSetType, resultSetConcurrency); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return con.prepareCall(sql, resultSetType, resultSetConcurrency); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return con.prepareStatement(sql, autoGeneratedKeys); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return con.prepareStatement(sql, columnIndexes); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return con.prepareStatement(sql, columnNames); } @Override public Clob createClob() throws SQLException { return con.createClob(); } @Override public Blob createBlob() throws SQLException { return con.createBlob(); } @Override public NClob createNClob() throws SQLException { return con.createNClob(); } @Override public SQLXML createSQLXML() throws SQLException { return con.createSQLXML(); } @Override public boolean isValid(int timeout) throws SQLException { return con.isValid(timeout); } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { con.setClientInfo(name, value); } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { con.setClientInfo(properties); } @Override public String getClientInfo(String name) throws SQLException { return con.getClientInfo(name); } @Override public Properties getClientInfo() throws SQLException { return con.getClientInfo(); } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { return con.createArrayOf(typeName, elements); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { return con.createStruct(typeName, attributes); } @Override public void setSchema(String schema) throws SQLException { con.setSchema(schema); } @Override public String getSchema() throws SQLException { return con.getSchema(); } @Override public void abort(Executor executor) throws SQLException { con.abort(executor); } @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { con.setNetworkTimeout(executor, milliseconds); } @Override public int getNetworkTimeout() throws SQLException { return con.getNetworkTimeout(); } @Override public <T> T unwrap(Class<T> iface) throws SQLException { return con.unwrap(iface); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return con.isWrapperFor(iface); } }
config.properties文件:
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db1
username=root
password=root