【狂神说Java】阶段三笔记3. MySQL-03

8 权限管理和备份

8.1 用户管理

  • SQL yog 可视化管理

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jatsD0e9-1614239947713)(C:\Users\Yy\AppData\Roaming\Typora\typora-user-images\image-20210222201210572.png)]

  • SQL 命令操作

用户表:mysql.user

本质:对这张表进行增删改查

-- 创建用户:CREATE USER 用户名 IDENTIFIED BY 密码
CREATE USER yuyang IDENTIFIED BY '123456'

-- 修改密码(当前用户密码)
SET PASSWORD = PASSWORD('123456')

-- 修改密码(指定用户密码)
SET PASSWORD FOR yuyang = PASSWORD('123456')

-- 重命名:RENAME USER 旧名字 TO 新名字
RENAME USER yuyang TO yuyang_yy

-- 用户授权:GRANT ALL PRIVILEGES(全部的权限) 库.表
-- ALL PRIVILEGES除了给别人授权,其他都能做
GRANT ALL PRIVILEGES ON *.* TO yuyang_yy  

-- 查询权限
SHOW GRANTS FOR `yuyang_yy`  -- 查看指定用户的权限
-- root用户权限:GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION
SHOW GRANTS FOR root@localhost 

-- 撤销权限:REVOKE 哪些权限 在哪个库 给谁撤销
REVOKE ALL PRIVILEGES ON *.* FROM `yuyang_yy`

-- 删除用户
DROP USER yuyang_yy

-- user表中Host栏写%代表任何ip都可访问此账户,远程用的

8.2 MySQL备份

  • 作用:保证重要的数据不丢失;sql(文本文件)数据转移

  • MySQL数据库备份的方式

    • 直接拷贝物理文件:D:\Environment\mysql-5.7.33-winx64\Data

    • 在SQLyog 可视化工具中手动导出

      • 在想要导出的表或者苦衷,右键,选择 备份/导出→备份表作为SQL转储
    • 使用cmd命令行导出:mysqldump

      # mysqldump -h 主机 -u 用户名 -p 密码 数据库 表名 > 物理磁盘位置/文件名
      mysqldump -hlocalhost -uroot -p123456 school student > D:/a.sql
      > mysqldump: [Warning] Using a password on the command line interface can be insecure.
      
      # mysqldump -h 主机 -u 用户名 -p 密码 数据库 表1 表2 表3 > 物理磁盘位置/文件名
      mysqldump -hlocalhost -uroot -p123456 school student result > D:/b.sql
      
      # mysqldump -h 主机 -u 用户名 -p 密码 数据库 > 物理磁盘位置/文件名
      mysqldump -hlocalhost -uroot -p123456 school > D:/c.sql
      
      # 导入:登陆的情况下,切换到指定数据库
      mysql> use school;
      mysql> source d:/a.sql  -- source 备份文件
      
      # 不登陆情况下
      mysql -u用户名 -p密码 库名 < 备份文件
      

9 规范数据库的设计

9.1 为什么需要设计数据库

当数据库比较复杂的时候,需要设计

  • 糟糕的数据库设计

    • 数据冗余,浪费空间
    • 数据库插入和删除都会麻烦、异常(屏蔽使用物理外键)
    • 程序的性能差
  • 良好的数据库设计

    • 节省内存设计
    • 保证数据库的完整设计
    • 方便我们开发系统
  • 软件开发中,关于数据库的设计

    • 分析需求:分析业务和需求处理的数据库需求
    • 概要设计:设计关系图E-R图
  • 设计数据库的步骤:(个人博客)

    • 收集信息,分析需求
      • 用户表(登录注销,个人信息,写博客,创建分类)
      • 分类表(文章分类,谁创建的)
      • 文章表(文章的信息)
      • 评论表
      • 友链表(友链信息)
      • 说说表(发表心情… id… content… create_time)
      • 自定义表(系统信息,某个关键的字,一些主字段key:value)
    • 标识实体(把需求落地到每个字段)
    • 标识实体之间的关系
      • 写博客:user -> blog
      • 创建分类:user -> category
      • 关注:user -> user
      • 友链:links
      • 评论:user -> user -> blog

bbs

crm

9.2 三大范式

  • 为什么需要数据规范化?

    信息重复;更新异常;插入异常(无法正常显示信息);删除异常(丢失有效的信息)

  • 三大范式

    目前关系数据库有六种范式:第一范式(1NF)、第二范式(2NF)、第三范式(3NF)、巴斯-科德范式(BCNF)、第四范式(4NF)和第五范式(5NF,又称完美范式)。而通常我们用的最多的就是第一范式(1NF)、第二范式(2NF)、第三范式(3NF),也就是“三大范式”。(规范数据库的设计)

  • 第一范式

    原子性:要求数据库表的每一列都是不可分割的原子数据项

  • 第二范式

    满足第一范式的前提下,每张表只描述一件事情

  • 第三范式

    满足第一范式和第二范式的前提下,第三范式需要确保数据表中的每一列数据都和主键之间相关,而不能间接相关

  • 规范性和性能的问题

    • 关联查询的表不得超过三张表,考虑商业化的需求和目标(成本,用户体验),数据库的性能更加重要
    • 在规范性能的问题时候,需要适当的考虑一下规范性
    • 故意给某些表增加一些冗余的字段(从多表查询中变为)
    • 故意增加一些计算列(从大数据量降低为小数据量的查询:增加索引)

10 JDBC(重点)

10.1 数据库驱动

驱动:声卡、显卡、数据库(我们的程序会通过数据驱动和数据库打交道)

在这里插入图片描述

10.2 JDBC

SUN公司为了简化开发人员对数据的统一操作,提供了一个Java操作数据的规范,俗称JDBC,这些规范的实现由具体的厂商去做。对于开发人员来说,我们只需要掌握JDBC接口的操作即可
在这里插入图片描述

java.sql

javax.sql

还需要导入一个数据库驱动包 mysql-connector-java-5.1.49.jar

Maven仓库jar包下载:https://mvnrepository.com/(输入mchange、c3p0、commons、mysql依次下载)

10.3 第一个JDBC程序

  • 创建测试数据库
CREATE DATABASE jdbcStudy CHARACTER SET utf8 COLLATE utf8_general_ci;
USE jdbcStudy;

CREATE TABLE `users`(
	id INT PRIMARY KEY,
	NAME VARCHAR(40),
	PASSWORD VARCHAR(40),
	email VARCHAR(60),
	birthday DATE
);

INSERT INTO `users`(id,NAME,PASSWORD,email,birthday)VALUES(1,'zhansan','123456','zs@sina.com','1980-12-04'),
(2,'lisi','123456','lisi@sina.com','1981-12-04'),(3,'wangwu','123456','wangwu@sina.com','1979-12-04')
  1. 创建一个普通项目
  2. 导入数据库驱动:将jar包复制到新建lib文件夹下,右键选择add as library
  3. 编写测试代码
//我的第一个JDBC程序
public class jdbcFirstDemo {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1. 加载驱动
        //DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 原来的方式
        Class.forName("com.mysql.jdbc.Driver");  // 固定写法,加载驱动

        //2. 用户信息和url
        /*
            useUnicode=true 支持中文编码
            characterEncoding=utf8 设定中文字符集
            useSSL=true 使用安全连接
         */
        String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false";
        String username = "root";
        String password = "123456";

        //3.连接成功,数据库对象 Connection代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);

        //4.执行SQL的对象 Statement 执行sql的对象
        Statement statement = connection.createStatement();

        //5.执行SQL的对象去执行SQL,可能存在结果,查看返回结果
        String sql = "SELECT * FROM users";
        ResultSet resultSet = statement.executeQuery(sql);  //执行,返回的结果集,结果集中,封装了我们全部的查询结果
        
        while (resultSet.next()){
            System.out.println("id = " + resultSet.getObject("id"));
            System.out.println("name = " + resultSet.getObject("NAME"));
            System.out.println("pwd = " + resultSet.getObject("PASSWORD"));
            System.out.println("email = " + resultSet.getObject("email"));
            System.out.println("birth = " + resultSet.getObject("birthday"));
        }  // 大小写相同

        //6.释放连接
        resultSet.close();
        statement.close();
        connection.close();
    }
}

步骤总结:

  1. 加载驱动
  2. 连接数据库DriverManager
  3. 获得执行sql的对象Stament
  4. 获得返回的结果集
  5. 释放连接
  • DriverManager
//DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 原来的方式
Class.forName("com.mysql.jdbc.Driver");  // 固定写法,加载驱动

Connection connection = DriverManager.getConnection(url, username, password);
//connnection 代表数据库:数据库设置自动提交、事务提交、事务回滚...
connection.rollback();
connection.commit();
connection.setAutoCommit();
  • URL
String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false";
// mysql 默认3306
// 协议://主机地址:端口号/数据库名?参数1&参数2&参数3
// oracle 默认 1521
// jdbc:oracle:thin:@localhost:1521:sid
  • Statement 执行SQL的对象(PrepareStatement执行SQL的对象)
Statement statement = connection.createStatement();
statement.executeQuery();  //查询操作,返回ResultSet
statement.execute();  // 执行任何SQL,效率会低
statement.executeUpdate();  // 更新、插入、删除都用这个,返回一个受影响的行数

String sql = "SELECT * FROM users";  // 编写SQL
  • ResultSet 查询的结果集:封装了所有的查询结果

获得数据类型

resultSet.getObject();  // 在不知道列类型的情况下使用
// 如果知道列的类型就是用指定的类型
resultSet.getString();
resultSet.getInt();
resultSet.getFloat();
resultSet.getDate();
...

遍历,指针

// [1, 1, 1, 1, 1, 1, 1, 1]
resultSet.beforeFirst();  // 移动到最前面
resultSet.afterLast();  // 移动到最后面
resultSet.next();  // 移动到下一个数据
resultSet.previous();  // 移动到前一行
resultSet.absolute(row);  // 移动到指定行

释放资源

resultSet.close();
statement.close();
connection.close();  // 耗资源,用完关掉

10.4 statement对象

jdbc中的statement对象用于想数据库发送SQL数据,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。

statement对象的executeUpdate方法,用于向数据库发送增、删、改的sql的语句,executeUpdate执行完毕后,将会放回一个整数(即增删改查语句导致了数据库几行数据发生了改变)。

statement.executeQuery方法用于向数据库发送查询语句,executeUpdate方法返回代表查询结果的ResultSet对象

  • CRUD操作:create

使用executeUpdate(String sql)方法完成数据添加操作,示例操作:

Statement st = connection.createStatement();
String sql = "insert into user(...) values(...)";
int num = st.executeUpdate(sql);
if(num > 0){
    System.out.println("插入成功!");
}
  • CRUD操作:delete

使用executeUpdate(String sql)方法完成数据删除操作,示例操作:

Statement st = connection.createStatement();
String sql = "delete from user where id = 1";
int num = st.executeUpdate(sql);
if(num < 0){
    System.out.println("删除成功!");
}
  • CRUD操作:update

使用executeUpdate(String sql)方法完成数据修改操作,示例操作:

Statement st = connection.createStatement();
String sql = "update user set name = '' where name = '' ";
int num = st.executeUpdate(sql);
if(num > 0){
    System.out.println("修改成功!");
}
  • CRUD操作:read

使用executeUpdate(String sql)方法完成数据查询操作,示例操作:

Statement st = connection.createStatement();
String sql = "select * from user where id = 1";
ResultSet rs = st.executeQuery(sql);
while (rs.next()){
    //根据获取列的数据类型,分别调用rs的相应方法映射到java对象中
}
  • 代码实现
  1. 提取工具类
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=123456
public class jdbcUtils {
    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;
    static {
        try{
            InputStream in = jdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(in);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");

            //1.驱动只用加载一次
            Class.forName(driver);

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

    //获取连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    //释放连接资源
    public static void release(Connection conn, Statement st, ResultSet rs) throws SQLException {
        if (rs != null){
            rs.close();
        }
        if (st != null){
            st.close();
        }
        if (conn != null){
            conn.close();
        }
    }
}
  1. 编写增删改的方法
public class TestInsert {
    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try{
            conn = jdbcUtils.getConnection();  //获取数据库连接
            st = conn.createStatement();  //获取SQL的执行对象
            String sql = "INSERT INTO users(id, `NAME`, `PASSWORD`, `email`, `birthday`) " +
                    "VALUES (4, 'kuangshen', '123456', '2436743@qq.com', '2020-01-01')";  // 只改写sql语句
            int i = st.executeUpdate(sql);
            if (i > 0){
                System.out.println("插入成功!");  //只需改写输出语句
            }
        } catch (SQLException e){
            e.printStackTrace();
        } finally{
            jdbcUtils.release(conn, st, rs);
        }
    }
}
public class TestSelect {
    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try{
            conn = jdbcUtils.getConnection();
            st = conn.createStatement();

            //SQL
            String sql = "SELECT * FROM users where id = 1";
            rs = st.executeQuery(sql);  //查询完毕会返回一个结果集

            while (rs.next()){
                System.out.println(rs.getString("NAME"));
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally{
            jdbcUtils.release(conn, st, rs);
        }
    }
}
  • SQL注入的问题

sql存在漏洞,会被攻击导致数据泄露,SQL会被拼接 or

public class SQL注入 {
    public static void main(String[] args) throws SQLException {
        //login("kuangshen", "123456");  //正常登录
        login(" ' or '1=1", " ' or '1=1");  // or
    }

    //登录业务
    public static void login(String username, String password) throws SQLException {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try{
            conn = jdbcUtils.getConnection();
            st = conn.createStatement();

            //SELECT * FROM `users` WHERE `NAME` = 'kuangshen' AND `PASSWORD` = '123456';
            //SELECT * FROM `users` WHERE `NAME` = ' ' or '1=1' AND `PASSWORD` = ' ' or '1=1';
            String sql = "SELECT * FROM users where `NAME` = '"+ username + "' AND `PASSWORD` = '"+ password + "'";
            rs = st.executeQuery(sql);  //查询完毕会返回一个结果集

            while (rs.next()){
                System.out.println(rs.getString("NAME"));
                System.out.println(rs.getString("PASSWORD"));
                System.out.println("====================");
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally{
            jdbcUtils.release(conn, st, rs);
        }
    }
}

10.5 PrepareStatement对象

PrepareStatement可以防止SQL注入,效率更高

  1. 增删改查
public class TestInsert {
    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try {
            conn = jdbcUtils.getConnection();

            //区别
            String sql = "INSERT INTO users(id, `NAME`, `PASSWORD`, `email`, `birthday`) VALUES (?, ?, ?, ?, ?)";
            st = conn.prepareStatement(sql);  // 预编译SQL,先写sql,然后不执行

            //手动给参数赋值
            st.setInt(1, 4);  //id
            st.setString(2, "qinjiang");  //name
            st.setString(3, "123456");  //pwd
            st.setString(4, "24734657@qq.com");  //emial
            //注意点:sql.Date   sql   java.sql.Date
            //       util.Date  java  new Date().getTime() 获得时间戳
            st.setDate(5, new java.sql.Date(System.currentTimeMillis()));  //date

            //执行
            int i = st.executeUpdate();
            if (i > 0){
                System.out.println("插入成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally{
            jdbcUtils.release(conn, st, rs);
        }
    }
}
public class TestSelect {
    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try {
            conn = jdbcUtils.getConnection();
            String sql = "select  * from users where id = ?";  //编写sql

            st = conn.prepareStatement(sql);  //预编译

            st.setInt(1, 2);  // 传递参数
            rs = st.executeQuery();   // 执行
            if (rs.next()){
                System.out.println(rs.getString("NAME"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally{
            jdbcUtils.release(conn, st, rs);
        }
    }
}
  1. 防止SQL注入
public class SQL注入 {
    public static void main(String[] args) throws SQLException {
        //login("lisi", "123456");  //正常登录
        login(" ' or 1=1", "123456");
    }

    //登录业务
    public static void login(String username, String password) throws SQLException {
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        try{
            conn = jdbcUtils.getConnection();

            //PreparedStatement防止SQL注入的本质:把传递进来的参数当作字符
            //假设其中存在转义字符,就直接忽略,’会被直接转义
            String sql = "SELECT * FROM users where `NAME` = ? and  `PASSWORD` = ?";  // Mybatis
            st = conn.prepareStatement(sql);
            st.setString(1, username);
            st.setString(2, password);

            rs = st.executeQuery();  // 查询完毕回返回一个结果集
            while (rs.next()){
                System.out.println(rs.getString("NAME"));
                System.out.println(rs.getString("PASSWORD"));
                System.out.println("====================");
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally{
            jdbcUtils.release(conn, st, rs);
        }
    }
}

10.6 使用IDEA连接数据库

  1. 连接数据库

在这里插入图片描述

  1. 连接成功后,添加数据库

在这里插入图片描述

  1. 双击数据库、表查看

  2. 更新数据:

在这里插入图片描述

  1. 编写SQL代码:

在这里插入图片描述

  1. 如果在IDEA中连接不上数据库,在这里修改为数据库对应的版本驱动

在这里插入图片描述

  • p43使用的表
/*创建账户表*/
CREATE TABLE account(
    id Int PRIMARY KEY AUTO_INCREMENT,
    NAME VARCHAR(40),
    money FLOAT
);

/*插入测试数据*/
insert into account(name,money) values('A',1000);
insert into account(name,money) values('B',1000);
insert into account(name,money) values('B',1000);

10.7 事务

要么都工程,要么都失败

  • ACID原则

    • 原子性:要么全部完成,谣么都不完成
    • 一致性:总数不变
    • 隔离性:多个进程互不干扰
      • 脏读:一个事务读取了另一个没有提交的事务
      • 不可重复读:在同一事物内,重复读取表中的数据,表数据发生了改变
      • 虚读(幻读):在一个事务内,读取到了别人插入的数据,导致前后读出来的结果不一致
    • 持久性:一旦提交不可逆,持久化到数据库了
  • 代码实现

    • 开启事务 conn.setAutoCommit(false);
    • 一组业务执行完毕,提交事务
    • 可以在catch语句中的显式的定义回滚语句,但默认失败就会回滚
public class TestTranscation1 {
    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try{
            conn = jdbcUtils.getConnection();
            //关闭数据库的自动提交,自动提交会开启事务
            conn.setAutoCommit(false);  // 开启事务
            String sql1 = "update account set money = money - 100 where name = 'A'";
            st = conn.prepareStatement(sql1);
            st.executeUpdate();

            //int x = 1/0;  //报错情况一条都没成功
            String sql2 = "update account set money = money + 100 where name = 'B'";
            st = conn.prepareStatement(sql2);
            st.executeUpdate();

            //业务完毕,提交事务
            conn.commit();
            System.out.println("成功");

        }catch (SQLException e){
//            try{
//                conn.rollback();  // 如果失败则回滚事务
//            }catch (SQLException e1){
//                e1.printStackTrace();
//            }
            //如果失败则默认回滚,不需要显式定义
            e.printStackTrace();
        }finally{
            jdbcUtils.release(conn, st, rs);
        }
    }
}

10.8 数据库连接池

数据库连接 → 执行完毕 → 释放

连接 → 释放,的过程十分浪费系统资源

池化技术:准备一些预先的资源,过来就连接预先准备好的(开门 → 业务员:等待 → 服务)

常用连接数:100; 最小连接数:100; 最大连接数:100(业务最高承载上线); 等待超时:100ms

编写连接池,实现一个接口DataSource

  • 开放数据源实现:使用了这些数据连接池之后,我们在项目开发中就不需要编写连接数据库的代码
    • DBCP
    • C3P0
    • Druid:阿里巴巴
  1. DBCP

需要用到的jar包:commons-dbcp-1.4.jar、commons-pool-1.6.jar

连接设置:

#连接设置 这里面的名字是DBCP数据源中定义好的
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=123456

#<!-- 初始化连接 -->
initialSize=10

#最大连接数量
maxActive=50

#<!-- 最大空闲连接 -->
maxIdle=20

#<!-- 最小空闲连接 -->
minIdle=5

#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000

#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:【属性名=property;】
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=UTF8

#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true

#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=

#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
public class JdbcUtils_DBCP {
    private static DataSource dataSource = null;

    static {
        try{
            InputStream in = JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
            Properties properties = new Properties();
            properties.load(in);

            //创建数据源 工厂模式:创建对象
            dataSource = BasicDataSourceFactory.createDataSource(properties);

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

    //获取连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();  //从数据源中获取连接
    }

    //释放连接资源
    public static void release(Connection conn, Statement st, ResultSet rs) throws SQLException {
        if (rs != null){
            rs.close();
        }
        if (st != null){
            st.close();
        }
        if (conn != null){
            conn.close();
        }
    }
}
  1. C3P0

需要用到的jar包:c3p0-0.9.5.5.jar、mchange-commons-java-0.2.20.jar

配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <!--
    c3p0的缺省(默认)配置
    如果在代码中"ComboPooledDataSource ds=new ComboPooledDataSource();"这样写就表示使用的是c3p0的缺省(默认)-->
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&amp;characterEncoding=utf8&amp;uesSSL=true&amp;serverTimezone=UTC</property>
        <property name="user">root</property>
        <property name="password">123456</property>

        <property name="acquiredIncrement">5</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">5</property>
        <property name="maxPoolSize">20</property>
    </default-config>

    <named-config name="MySQL">
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&amp;characterEncoding=utf8&amp;uesSSL=true&amp;serverTimezone=UTC</property>
        <property name="user">root</property>
        <property name="password">123456</property>

        <property name="acquiredIncrement">5</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">5</property>
        <property name="maxPoolSize">20</property>
    </named-config>

</c3p0-config>
public class JdbcUtils_C3P0 {
    private static ComboPooledDataSource dataSource = null;

    static {
        try{
//            dataSource = new ComboPooledDataSource();  //代码版配置
//            dataSource.setDriverClass();
//            dataSource.setUser();
//            dataSource.setPassword();
//            dataSource.setJdbcUrl();
//            dataSource.setMaxPoolSize();
//            dataSource.setMinPoolSize();

            dataSource = new ComboPooledDataSource("MySQL");  //配置文件写法

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

    //获取连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();  //从数据源中获取连接
    }

    //释放连接资源
    public static void release(Connection conn, Statement st, ResultSet rs) throws SQLException {
        if (rs != null){
            rs.close();
        }
        if (st != null){
            st.close();
        }
        if (conn != null){
            conn.close();
        }
    }
}
  1. 结论

无论使用什么数据源,本质还是一样的,DataSource接口是不变的,方法就不会变

Druid

Apache:https://www.apache.org/index.html#projects-list

— 业务级别的MySQL: 8、9、10

— 运维级别的MySQL

PS:学习自狂神说java

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值