目录
- package demo02.myDataSourse;
- import demo02.utils.JDBCUtils;
-
- 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 demoDataSourse implements DataSource{
- //1.准备容器,用于保存多个连接对象
- private static List
pool = Collections.synchronizedList(new ArrayList<>()); - //2.定义静态代码块,通过工具类获取10个连接对象
- static{
- for(int i=1;i<=10;i++){
- Connection con = JDBCUtils.getConnection();
- pool.add(con);
- }
- }
- //3.重写getConnection(),用于获取一个连接对象
- @Override
- public Connection getConnection() throws SQLException {
- if(pool.size()>0){
- Connection con = pool.remove(0);
- return con;
- }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 unwrap(Class 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;
- }
- }
- package demo02.myDataSourse;
-
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
-
- public class demoDataSourseTest {
- public static void main(String[] args) throws Exception {
- //1.创建连接池对象
- demoDataSourse dataSourse = new demoDataSourse();
-
- System.out.println("使用之前的数量" + dataSourse.getSize());
-
- //2.通过连接池对象获取连接对象
- Connection con = dataSourse.getConnection();
- //3.查询学生表的全部信息
- String sql = "SELECT * FROM student";
- PreparedStatement pst = con.prepareStatement(sql);
- //4.执行sql语句,接收结果集
- ResultSet rs = pst.executeQuery();
- //5.处理结果集
- while(rs.next()){
- System.out.println(rs.getInt("sid")+"\t"+rs.getString("name")+"\t"+rs.getInt("age")+"\t"+rs.getDate("birthday"));
- }
- //6.释放资源
- rs.close();
- pst.close();
- con.close();//用完以后,未归还进行关闭连接;归还后面再讲
-
- System.out.println("使用之后的数量" + dataSourse.getSize());
- }
- }