數據庫連接池c3p0數據庫連接池

1.前提準備:

1.1創建數據庫

use day04_db;
create table user (
  id int primary key auto_increment,
  username varchar(20) not null,
  birthday date,
  sex char(1) default '男',
  address varchar(50)
);

insert into user values (null, '孫悟空','1980-10-24','男','花果山水簾洞');
insert into user values (null, '白骨精','1992-11-12','女','白虎嶺白骨洞');
insert into user values (null, '豬八戒','1983-05-20','男','福臨山雲棧洞');
insert into user values (null, '蜘蛛精','1995-03-22','女','盤絲洞');

select * from user;

1.2創建實體類對象


package cn.itcast.domain;

import java.util.Date;

public class User {
    private  Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}


1.3 JDBC工具類

jdbc。properties文件

url=jdbc:mysql://localhost/day04_db
username=root
password=root
driverClass=com.mysql.jdbc.Driver


package cn.itcast.utils;

import javax.xml.transform.Result;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    //思路:方便對數據庫的使用,省去了大量的創建連接數據庫使用語句
    //基本步驟
    //1.對基本的語句抽取成靜態代碼塊
    //2.創建連接的方法
    //創建銷燬的方法
    private static  String driverClass;
    private static  String url;
    private static String username;
    private static String password;
    static {
        try {
            Properties properties= new Properties();
            properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            driverClass = properties.getProperty("driverClass");
            url = properties.getProperty("url");
            username= properties.getProperty("username");
            password= properties.getProperty("password");
            Class.forName(driverClass);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void release(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (connection != null) {
                connection.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



2.基於jdbc工具類將數據封裝到實體類中


package cn.itcast.test;

import cn.itcast.domain.User;
import cn.itcast.utils.JDBCUtils;
import org.omg.CORBA.UserException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class JDBCText03 {


    public static void main(String[] args) throws Exception {
        List<User> list = new ArrayList<User>();
        Connection connection = JDBCUtils.getConnection();
        String sql  ="select * from user";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            Integer id = resultSet.getInt("id");
            String username = resultSet.getString("username");
            Date birthday = resultSet.getDate("birthday");
            String sex = resultSet.getString("sex");
            String address = resultSet.getString("address");
            User user = new User();
            user.setId(id);
            user.setUsername(username);
            user.setBirthday(birthday);
            user.setSex(sex);
            user.setAddress(address);
            list.add(user);
        }
        for (User user : list) {
            System.out.println(user);
        }
        JDBCUtils.release(connection,preparedStatement,resultSet);

    }

}


查詢結果

在這裏插入圖片描述

3.c3p0連接池的使用

使用連接池的好處:面試題
優化了連接,省去了創建連接與銷燬鏈接的時間,提高了增刪改查的效率、

3.1c3p0的使用步驟

c3p0連接池的使用步驟
1.創建項目
2.創建lib文件夾,導入c3p0依賴包 add as libery加載到項目中
創建c3p0核心配置文件,連接數據庫
創建jdbc.properties文件保存四大內置對象
編寫測試類
創建連接池的好處:省去了創建連接歸還鏈接所用的時間,大大提升了效率
優化了創建連接所用的時間

3.2創建項目導包

在這裏插入圖片描述
還有MySQL的驅動包

3.3創建核心配置文件

在src目錄下創建


<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost/day04_db</property>
        <property name="user">root</property>
        <property name="password">root</property>

    </default-config>
    <named-config name="intergalactoApp">

    </named-config>
</c3p0-config>

3.4創建測試類

package cn.itcast.web;

import cn.itcast.utils.JDBCUtils;
import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Demo01 {
    public static void main(String[] args) throws Exception {
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        Connection connection = comboPooledDataSource.getConnection();
        String sql = "select * from user";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            String id = resultSet.getString("id");
            String username = resultSet.getString("username");
            String birthday = resultSet.getString("birthday");
            String sex = resultSet.getString("sex");
            String address = resultSet.getString("address");
            System.out.println(id + username + birthday + sex + address);
        }
        JDBCUtils.release(connection,preparedStatement,resultSet);
    }
}



3.5根據id查詢


@Test
    public void test01() throws Exception {
        //根據id查詢
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        Connection connection = comboPooledDataSource.getConnection();
        String sql = "select * from user where id=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, 1);
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            String id = resultSet.getString("id");
            String username = resultSet.getString("username");
            String birthday = resultSet.getString("birthday");
            String sex = resultSet.getString("sex");
            String address = resultSet.getString("address");
            System.out.println(id + username + birthday + sex + address);
        }
        JDBCUtils.release(connection,preparedStatement,resultSet);
    }


3.6添加數據

@Test
    public void test02() throws Exception {
        //添加
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        Connection connection = comboPooledDataSource.getConnection();
        String sql="insert into user values(null,?,?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, "王五");
        preparedStatement.setString(2, "2020-01-01");
        preparedStatement.setString(3, "男");
        preparedStatement.setString(4, "廣州");
        int i = preparedStatement.executeUpdate();
        if (i == 1) {
            System.out.println("添加成功");
        } else {
            System.out.println("添加失敗");
        }

        JDBCUtils.release(connection,preparedStatement,null);
    }



3.7修改數據


 @Test
    public void test03() throws Exception {
        //修改
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        Connection connection = comboPooledDataSource.getConnection();
        String sql = "update user set username=? ,birthday=? ,sex=? where id=? ";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, "全威");
        preparedStatement.setString(2, "2020-01-01");
        preparedStatement.setString(3, "男");
        preparedStatement.setInt(4, 11);
        int i = preparedStatement.executeUpdate();
        if (i == 1) {
            System.out.println("修改成功");
        } else {
            System.out.println("修改失敗");
        }
        JDBCUtils.release(connection, preparedStatement, null);
    }

3.8刪除數據

@Test
    public void test05() throws Exception {
        //刪除
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        Connection connection = comboPooledDataSource.getConnection();
        String sql = "delete from user where id=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, 12);
        int i = preparedStatement.executeUpdate();
        if (i == 1) {
            System.out.println("刪除成功");
        } else {
            System.out.println("刪除失敗");
        }
        JDBCUtils.release(connection, preparedStatement, null);
    }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章