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

2017-08-26  本文已影响187人  张不二01

本篇包括如下内容:


1,JDBC及封装(Java DataBase Connectivity)
  • 注意使用前需要先引入相应的包
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();
}
  • 既然是对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的封装)
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);
QueryRunner runner = new QueryRunner(DBCPUtil.getDataSource());

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

3,自定义连接池(使用装饰者模式进行加强)
//1,自定义连接池
/*
 * 对JDBC连接的封装,也就是自定义连接池
 * 其他一些方法也需要重写,但是不需要任何改变,所以这里就没有贴出来
 */
public class JDBCDatasource implements DataSource {
    private static LinkedList<Connection> connections = new LinkedList<Connection>();
    //往连接池中添加连接
    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<Connection> connections;
    public JDBCConnection(List<Connection> connections, Connection connection) {
        this.connections = (LinkedList<Connection>) 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连接池使用(连接池可以提高数据库使用效率)

需要导入包和配置文件
使用代码如下:
配合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);
}

需要导入包和配置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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读