JDBC及封装,DBUtil使用,自定义连接池,c3p0和dbcp连接池使用

本篇包括如下内容:

  • ** 1,JDBC及封装,**
  • 2,DBUtil使用,
  • 3,自定义连接池,
  • 4,c3p0和dbcp连接池使用

1,JDBC及封装(Java DataBase Connectivity)
  • 1.1, JDBC的使用
  • 注意使用前需要先引入相应的包
  • 在查询的时候用PreparedStatement这个比较安全,如果用Statement有插入攻击的危险
try {
    //1,注册驱动
    Class.forName("com.mysql.jdbc.Driver");
    
    //2,获取连接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ivanl?autoReconnect=true&useSSL=false&characterEncoding=utf-8", "root", "0.");
    
    //3,通过连接进行查询
    PreparedStatement preparedStatement = connection.prepareStatement("select * from t_product");
    ResultSet set = preparedStatement.executeQuery();
    while(set.next()){
        System.out.println(set.getString("name") + "  " + set.getDouble("price"));
    }
    
    //4,关闭资源
    set.close();
    preparedStatement.close();
    connection.close();
    
} catch (Exception e) {
    e.printStackTrace();
}
  • 1.2, JDBC的自定义封装
  • 既然是对jdbc的封装,也需要先引入必要的包
  • 因为驱动注册和获取连接池以及关闭资源所有的数据库操作都是一致的,所以驱动注册和获取连接池直接用静态方法进行封装,只读取一次,关闭资源传入参数进行关闭

读取配置文件资源的时候,如果是java项目,有两种方式:Properties和ResourceBundle,代码有体现

package im.jdbcutil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ResourceBundle;

public class JDBCUtil {
    
    public static String driver;
    public static String url;
    public static String username;
    public static String pwd;
  
    static{
        try {
            /*
            Properties properties = new Properties();
            FileInputStream inputStream = new FileInputStream("src/database.properties");
            properties.load(inputStream);
            driver = properties.getProperty("driverClass");
            url = properties.getProperty("url");
            username = properties.getProperty("user");
            pwd = properties.getProperty("password");
            */

            ResourceBundle bundle = ResourceBundle.getBundle("database");
            driver = bundle.getString("driverClass");
            url = bundle.getString("url");
            username = bundle.getString("user");
            pwd = bundle.getString("password");
            
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public static Connection getConnection(){
        try {
            //1,注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2,获取连接
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/ivanl?autoReconnect=true&useSSL=false&characterEncoding=utf-8", "root", "0.");
        } catch (Exception e) {
            System.out.println("获取连接失败");
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    
    public static void closeAll(Connection connection, PreparedStatement statement, ResultSet resultSet){
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (Exception e) {
            System.out.println("结果集资源释放失败");
            e.printStackTrace();
        }
        
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (Exception e) {
            System.out.println("sql声明资源释放失败");
            e.printStackTrace();
        }
        
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            System.out.println("连接集资源释放失败");
            e.printStackTrace();
        }
    }
}

数据库配置文件database.properties内容:

driverClass = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/test01?autoReconnect=true&useSSL=false&characterEncoding=utf-8
user = root
password = 0.

2,DBUtil使用(对JDBC的封装)
  • DBUtil创建QueryRunner的时候有两种方式:空参构建和数据库构建

  • DBUtil有很多种类型的结果集,比如返回数组,字典,模型等等,文档中都有比较详细介绍,如果不太懂的话可以看一下文档

  • DBUtil既然架包,那么在使用的时候必然需要先导包

  • 2.1,空参构建方式,其中在执行语句的时候需要传入连接,我这里直接使用1.2中封装方法获取连接,可以保证只获取一次*
Connection connection = JDBCUtil.connection;
String sqlStr = "insert into t_ivanl001 (name, age, num) values (?, ?, ?)";
QueryRunner queryRunner = new QueryRunner();
try {
     Object[] params = {name, age, num};
     queryRunner.update(connection, sqlStr, params);
} catch (SQLException e) {
    System.out.println("数据插入失败!");
    e.printStackTrace();
} 
DbUtils.closeQuietly(connection);
  • 2.2,数据库构建构建方式,构建时候需要直接传入一个数据源,数据源可以通过c3p0或dbcp连接池获得,这是后面的内容,这里先不涉及*
QueryRunner runner = new QueryRunner(DBCPUtil.getDataSource());

try {
     List products = runner.query("select * from product", new BeanListHandler(Product.class));
     System.out.println(products);
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    
}

3,自定义连接池(使用装饰者模式进行加强)
//1,自定义连接池
/*
 * 对JDBC连接的封装,也就是自定义连接池
 * 其他一些方法也需要重写,但是不需要任何改变,所以这里就没有贴出来
 */
public class JDBCDatasource implements DataSource {
    private static LinkedList connections = new LinkedList();
    //往连接池中添加连接
    static{
        for(int i=0;i<5;i++){
            Connection connection = JDBCUtil.getConnection();
            JDBCConnection theConnection = new JDBCConnection(connections, connection);
            connections.add(theConnection);
        }
    }
    //重写这一个方法,如果没有增强过connection的话,需要调用这个方法归还连接到连接池中
    @Override
    public Connection getConnection() throws SQLException {
        if (connections.size() == 0) {
            for(int i=0;i<5;i++){
                Connection connection = JDBCUtil.getConnection();
                JDBCConnection theConnection = new JDBCConnection(connections, connection);
                connections.add(theConnection);
            }
        }
        return connections.removeFirst();
    }
     //新增一个方法
    public void returnConnection(Connection connection){
        connections.add(connection);
    }
}

//2,自定义连接类,实现相应的方法,并在自定义的连接池中进行包装,具体看1中的代码
//其他一些不需要修改的覆盖方法这里不再贴出
public class JDBCConnection implements Connection {
    private Connection connection;
    private LinkedList connections;
    public JDBCConnection(List connections, Connection connection) {
        this.connections = (LinkedList) connections;
        this.connection = connection;
    }
    //如果想要在关闭的时候添加到连接池,那么需要把连接池传进来,传进来最好的时候就是创建的时候
    @Override
    public void close() throws SQLException {
        System.out.println("here here!");
        connections.add(connection);
    }
    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }
}

//测试
JDBCDatasource datasource = new JDBCDatasource();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
    connection = datasource.getConnection();
    preparedStatement = connection.prepareStatement("select * from product;");
    resultSet = preparedStatement.executeQuery();
    while(resultSet.next()){
        System.out.println(resultSet.getString("pname"));
    }
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    //这行代码中封装了connection.close()方法
    JDBCUtil.closeAll(connection, preparedStatement, resultSet);
}
4,c3p0和dbcp连接池使用(连接池可以提高数据库使用效率)
  • 4.1,c3p0

需要导入包和配置文件
使用代码如下:
配合DBUtils使用的时候可以直接传入连接池进行使用,也可以传入连接使用,见上面的DBUtils的使用

//也可以把c3p0封装后直接获取连接池和连接,我这里直接使用
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;

DataSource dataSource = new ComboPooledDataSource();
try {
    connection = dataSource.getConnection();
    String sqlStr = "select * from product";
    preparedStatement = connection.prepareStatement(sqlStr);
    resultSet = preparedStatement.executeQuery();
    
    while(resultSet.next()){
        System.out.println(resultSet.getString("pname"));
    }
} catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} finally {
    JDBCUtil.closeAll(connection, preparedStatement, resultSet);
}

  • 4.2,dbcp

需要导入包和配置properties文件
使用代码如下:

Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;

connection = DBCPUtil.getConnection();
try {
    preparedStatement = connection.prepareStatement("select * from product");
    resultSet = preparedStatement.executeQuery();
    
    while(resultSet.next()){
        System.out.println(resultSet.getString("pname"));
    }
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    JDBCUtil.closeAll(connection, preparedStatement, resultSet);
}

其中上面用到的DBCPUtilde封装如下:

package im.dbcputils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

/*
 * 这里是使用默认的配置标准进行配置后读取文件
 */
public class DBCPUtil {

    private static DataSource dataSource;
    
    static{
        try {
            InputStream inputStream = DBCPUtil.class.getClassLoader().getResourceAsStream("database.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    public static DataSource getDataSource() {
        return dataSource;
    }
    
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}

你可能感兴趣的:(JDBC及封装,DBUtil使用,自定义连接池,c3p0和dbcp连接池使用)