数据库开发(2)

第三章.JDBC

1.JDBC介绍

1.问题:
  将来我们主要写java代码的,我们操作数据库的时候,不能只在sqlyog中写sql语句,我们应该将sql语句放到java代码中,使用java代码中的api去执行sql语句,从而操作数据库
  我们怎么用javaAPI去操作sql语句呢?就需要用到JDBC技术
      
2.JDBC概述(JAVA DATABASE Connection):数据库连接技术,JDBC是一个标准,在这一套标准中定义了好多接口,以及方法,这些接口和方法就是用于操作数据库的API


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rjCPZAuf-1659014506274)(D:\Typora\bin\document\img\1656725978170.png)]

2.JDBC准备(导入jar包)

1.导入jar包-> 凡是操作数据库,所有的操作都依赖一个核心jar包
  mysql-connector-java-8.0.25.jar
2.如何导jar包:
  a.创建lib,将jar包复制进去
  b.右键->add as library
  c.level中选择module
  d.点ok
      
3.使用jdbc,需要学习4大核心接口
  DriverManager-> 设置数据库驱动的
  Connection      接口 -> 连接数据库
  Statement       接口 -> 操作数据库
  ResultSet       接口 -> 结果集 -> 将查询出的结果封装到此对象中,我们再从里面获取查询出来的数据


3.JDBC开发步骤以及详解

1.注册驱动:  DriverManager2.获取连接(Connection接口):用到DriverManager类中的静态方法
  Connection getConnection(数据库url,用户名,密码)
    
3.准备sql语句:写一条sql语句,放到String4.获取执行平台(Statement接口):用到的是Connection接口中的方法
  Statement createStatement()
    
5.执行sql:用到的是Statement中的方法:
  int executeUpdate(String sql)   -> 针对于增删改操作
  ResultSet executeQuery(String sql)  ->针对于查询操作    
      
6.处理结果集(ResultSet接口):
  a.针对于增删改操作不用处理结果集
  b.针对于查询操作需要处理结果集-> 遍历结果集
      
7.关闭资源:统一方法->  close()
  a.ResultSet关闭
  b.Statement关闭
  c.Connection关闭


4.JDBC注册驱动

CREATE TABLE `user`(
  uid INT PRIMARY KEY AUTO_INCREMENT,
  username VARCHAR(10),
  `password` VARCHAR(20)
);


     1.注册驱动:DriverManager中的方法
           static void registerDriver(Driver driver)
         2.参数:Driver接口 -> java.sql包 -> 传递Driver接口的实现类对象

           a.从API文档上看,没有记录Driver的实现类
           b.去导入的mysql核心jar包中去找Driver的实现类
             com.mysql.cj.jdbc.Driver
             
         3.问题:我们要是直接传递com.mysql.cj.jdbc.Driver,Driver加载到内存之后
               Driver中的静态代码块也要执行了,在静态代码块中也写了一句 DriverManager.registerDriver(new Driver());
               也就是相当于我们注册了2,我们只需要注册一次就好了
               
         4.怎么注册一次?->我们只需要使用com.mysql.cj.jdbc.Driver帮我们注册驱动就好了
           还需要想办法将com.mysql.cj.jdbc.Driver加载到内存即可->反射
           
         5.反射这个com.mysql.cj.jdbc.Driver
           Class.forName("com.mysql.cj.jdbc.Driver");     


Class.forName("com.mysql.cj.jdbc.Driver");


5.JDBC获取连接

 2.获取连接:DriverManager中的静态方法:
   static Connection getConnection(String url, String user, String password)

   a.参数说明:
     url:数据库地址-> jdbc:mysql://localhost:3306/数据库名字?参数&参数
     user:数据库用户名
     password:数据库密码

   b.url细节问题:
     ?前面写的是地址
     ?后面写的是其他参数->key=value形式->多个键值对之间用&连接


String url = "jdbc:mysql://localhost:3306/220526_java_03";
String username = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println(connection);


常见问题说明:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l3alF0BY-1659014506275)(D:\Typora\bin\document\img\1656729766536.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0cG5lNlD-1659014506276)(D:\Typora\bin\document\img\1656729818958.png)]

6.JDBC实现增删改操作

public class Test01 {
    public static void main(String[] args)throws Exception {
        /*
         1.注册驱动:DriverManager中的方法
           static void registerDriver(Driver driver)
         2.参数:Driver接口 -> java.sql包 -> 传递Driver接口的实现类对象

           a.从API文档上看,没有记录Driver的实现类
           b.去导入的mysql核心jar包中去找Driver的实现类
             com.mysql.cj.jdbc.Driver

         3.问题:我们要是直接传递com.mysql.cj.jdbc.Driver,当Driver加载到内存之后
               Driver中的静态代码块也要执行了,在静态代码块中也写了一句 DriverManager.registerDriver(new Driver());
               也就是相当于我们注册了2次,我们只需要注册一次就好了

         4.怎么注册一次?->我们只需要使用com.mysql.cj.jdbc.Driver帮我们注册驱动就好了
           还需要想办法将com.mysql.cj.jdbc.Driver加载到内存即可->反射

         5.反射这个com.mysql.cj.jdbc.Driver
           Class.forName("com.mysql.cj.jdbc.Driver");

         */

        Class.forName("com.mysql.cj.jdbc.Driver");

        /*
          2.获取连接:DriverManager中的静态方法:
            static Connection getConnection(String url, String user, String password)

            a.参数说明:
              url:数据库地址-> jdbc:mysql://localhost:3306/数据库名字?参数&参数
              user:数据库用户名
              password:数据库密码

            b.url细节问题:
              ?前面写的是地址
              ?后面写的是其他参数->key=value形式->多个键值对之间用&连接
         */

        String url = "jdbc:mysql://localhost:3306/220526_java_03";
        String username = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, username, password);

        /*
          3.写sql语句
         */
        String sql = "insert into user (username,password) values ('tom','123')";

        /*
          4.获取执行平台:Statement接口
            用到的是Connection接口中的方法:
              Statement createStatement()
         */
        Statement st = connection.createStatement();
        /*
          5.执行sql:用到的是Statement中的方法:
            int executeUpdate(sql)-> 执行增删改操作
            ResultSet executeQuery(sql)-> 执行查询操作
         */
        int i = st.executeUpdate(sql);
        System.out.println(i);

        //6.处理结果集->只有查询才会处理结果集
        //7.关闭资源
        st.close();
        connection.close();
    }
}
  


 @Test
    public void delete() throws Exception {
        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取连接
        String url = "jdbc:mysql://localhost:3306/220526_java_03";
        String username = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, username, password);

        //3.准备sql
        String sql = "delete from user where uid = 1";

        //4.获取执行平台
        Statement statement = connection.createStatement();

        //5.执行sql
        statement.executeUpdate(sql);

        //6.关闭资源
        statement.close();
        connection.close();
    } 


    @Test
    public void update()throws Exception{
        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取连接
        String url = "jdbc:mysql://localhost:3306/220526_java_03";
        String username = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, username, password);

        //3.准备sql
        String sql = "update user set password = '666' where uid = 2";

        //4.获取执行平台
        Statement statement = connection.createStatement();

        //5.执行sql
        statement.executeUpdate(sql);

        //6.关闭资源
        statement.close();
        connection.close();
    }


如果我们在java中写的sql语句不保证是否正确:

1.现在java代码中写上sql语句,然后粘贴到sqlyog中执行一下

2.直接先在sqlyog中写出sql语句,然后测试,如果正确,粘贴到java代码中

注意:

在java代码中写sql语句其实和关键字冲突的名字,不用非得加``

7.JDBC实现查询操作

1.查询所用的方法:
  ResultSet executeQuery(String sql)
2.处理结果集:
  ResultSet中的方法:
  a.boolean next()-> 判断有没有下一个数据
  b.int getInt(int columnIndex)  
               columnIndex:指的是第几列数据
    int getInt(String columnLabel) 
               columnLabel:列名
                   
  c.String getString(int columnIndex)  
                     columnIndex:指的是第几列数据
    String getString(String columnLabel)  
                      columnLabel:列名
                          
  d.Object getObject(int columnIndex) 
                     columnIndex:指的是第几列数据
    Object getObject(String columnLabel)  
                     columnLabel:列名


 @Test
    public void find()throws Exception{
        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取连接
        String url = "jdbc:mysql://localhost:3306/220526_java_03";
        String username = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, username, password);

        //3.准备sql
        String sql = "select * from user";

        //4.获取执行平台
        Statement statement = connection.createStatement();

        //5.执行sql
        ResultSet rs = statement.executeQuery(sql);

        //6.处理结果集
        while(rs.next()){
            //int id = rs.getInt(1);
            //int id = rs.getInt("uid");
           // int id = rs.getInt("username");username是字符串,不能用getInt方法

            //String name = rs.getString("username");

            Object uid = rs.getObject("uid");
            Object name = rs.getObject("username");
            Object pwd = rs.getObject("password");
            System.out.println(uid+"..."+name+"..."+pwd);
        }

        //7.关闭资源
        statement.close();
        connection.close();
        rs.close();
    }


8.JDBC工具类使用

/**
 *  jdbc的工具类
 */
public class JDBCUtils {

    private static String url = null;
    private static String username = null;
    private static String password = null;

    //四大参数需要最先执行,而且只执行一次就好了
    static{
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            url = "jdbc:mysql://localhost:3306/220526_java_03";
            username = "root";
            password = "root";
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    //定义方法,用来获取连接
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //关闭资源
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}



public class Test03 {
    @Test
    public void delete() throws Exception {
        //获取连接
        Connection connection = JDBCUtils.getConnection();

        //3.准备sql
        String sql = "delete from user where uid = 2";

        //4.获取执行平台
        Statement statement = connection.createStatement();

        //5.执行sql
        statement.executeUpdate(sql);

        //6.关闭资源
        JDBCUtils.close(connection,statement,null);
    }

    @Test
    public void update()throws Exception{
        Connection connection = JDBCUtils.getConnection();

        //3.准备sql
        String sql = "update user set password = '666' where uid = 3";

        //4.获取执行平台
        Statement statement = connection.createStatement();

        //5.执行sql
        statement.executeUpdate(sql);

        //6.关闭资源
        JDBCUtils.close(connection,statement,null);
    }

    /**
     * 查询
     */

    @Test
    public void find()throws Exception{
        Connection connection = JDBCUtils.getConnection();
        //3.准备sql
        String sql = "select * from user";

        //4.获取执行平台
        Statement statement = connection.createStatement();

        //5.执行sql
        ResultSet rs = statement.executeQuery(sql);

        //6.处理结果集
        while(rs.next()){
            //int id = rs.getInt(1);
            //int id = rs.getInt("uid");
           // int id = rs.getInt("username");username是字符串,不能用getInt方法

            //String name = rs.getString("username");

            Object uid = rs.getObject("uid");
            Object name = rs.getObject("username");
            Object pwd = rs.getObject("password");
            System.out.println(uid+"..."+name+"..."+pwd);
        }

        //7.关闭资源
        JDBCUtils.close(connection,statement,rs);
    }
}



第四章.PreparedStatement预处理对象

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ypkOr7Aw-1659014506277)(D:\Typora\bin\document\img\1656744239601.png)]

1.sql注入的问题以及解决方式(预处理对象)

public class Test01 {
    public static void main(String[] args)throws Exception {
        //1.键盘录入一个用户名和密码
        Scanner sc = new Scanner(System.in);
        //2.录入用户名和密码
        System.out.println("请您输入一个用户名:");
        String username = sc.nextLine();
        System.out.println("请您输入一个密码:");
        String password = sc.nextLine();
        //3.获取连接
        Connection connection = JDBCUtils.getConnection();
        //4.获取执行平台
        Statement statement = connection.createStatement();
        //5.准备sql
        /*
           String sql =  "select * from user where username = 'jack' and password = '666'"

           "select * from user where username = '"+username+"' and password = '"+password+"'"

         */
        String sql = "select * from user where username = '"+username+"' and password = '"+password+"'";
        System.out.println(sql);
        //6.执行sql
        ResultSet rs = statement.executeQuery(sql);
        //7.处理结果集判断
        if (rs.next()){
            System.out.println("登录成功");
        }else{
            System.out.println("登录失败");
        }
        //8.关闭资源
        JDBCUtils.close(connection,statement,rs);
    }
}



密码输入:345’ or ‘1’ = '1 以上程序不行了->sql注入

2.使用预处理对象(PreparedStatement)实现操作

1.概述:PreparedStatementStatement的子接口
2.获取:Connection中的方法
  PreparedStatement prepareStatement(String sql)  
3.特点:
  支持sql语句中写占位符->   ?
  select * from user where username = ? and password = ?
4.?赋值:
  void setObject(int parameterIndex, Object x)  
  a.parameterIndex:写的是给第几个?赋值
  b.x:?赋的值  
      
5.执行sql方法:
  int executeUpdate() -> 针对于增删改操作
  ResultSet executeQuery()  -> 针对于查询

3.使用预处理对象(PreparedStatement)实现查询操作

public class Test01 {
    public static void main(String[] args)throws Exception {
        //1.键盘录入一个用户名和密码
        Scanner sc = new Scanner(System.in);
        //2.录入用户名和密码
        System.out.println("请您输入一个用户名:");
        String username = sc.nextLine();
        System.out.println("请您输入一个密码:");
        String password = sc.nextLine();
        //3.获取连接
        Connection connection = JDBCUtils.getConnection();

        String sql = "select * from user where username = ? and password = ?";
        //4.获取执行平台
        PreparedStatement pst = connection.prepareStatement(sql);

        System.out.println(sql);

        //5.为?赋值
        pst.setObject(1,username);
        pst.setObject(2,password);

        //6.执行sql
        ResultSet rs = pst.executeQuery();
        //7.处理结果集判断
        if (rs.next()){
            System.out.println("登录成功");
        }else{
            System.out.println("登录失败");
        }
        //8.关闭资源
        JDBCUtils.close(connection,pst,rs);
    }
}


1.不使用PreparedStatement:
  select * from user where username = 'jack' and password = '345' or '1' = '1'
      
2.使用了 PreparedStatement
  select * from user where username = 'jack' and password = '345\' or \'1\' = \'1' 
      
  会将录入的内容自动加上转移字符,此时我们在控制台上录入的'就是普通的字符内容了,就不是那个具有特殊含义的单引号了

    @Test
    public void add()throws Exception{
        Connection connection = JDBCUtils.getConnection();
        String sql = "insert into user (username,password) values (?,?)";
        PreparedStatement pst = connection.prepareStatement(sql);
        pst.setObject(1,"tom");
        pst.setObject(2,"abc");
        pst.executeUpdate();
        JDBCUtils.close(connection,pst,null);
    }

   @Test
    public void delete()throws Exception{
        Connection connection = JDBCUtils.getConnection();
        String sql = "delete from user where uid = ?";
        PreparedStatement pst = connection.prepareStatement(sql);
        pst.setObject(1,"6");
        pst.executeUpdate();
        JDBCUtils.close(connection,pst,null);
    }

  @Test
    public void update()throws Exception{
        Connection connection = JDBCUtils.getConnection();
        String sql = "update user set username = ? where uid = ?";
        PreparedStatement pst = connection.prepareStatement(sql);
        pst.setObject(1,"柳岩");
        pst.setObject(2,"7");
        pst.executeUpdate();
        JDBCUtils.close(connection,pst,null);
    }

   @Test
    public void find()throws Exception{
        Connection connection = JDBCUtils.getConnection();
        String sql = "select * from user";
        PreparedStatement pst = connection.prepareStatement(sql);
        ResultSet resultSet = pst.executeQuery();
        while(resultSet.next()){
            Object uid = resultSet.getObject("uid");
            Object username = resultSet.getObject("username");
            Object password = resultSet.getObject("password");

            System.out.println(uid+"..."+username+"..."+password);
        }
        JDBCUtils.close(connection,pst,resultSet);
    }


第五章.改造JDBC工具类_结合Properties文件

driverClass=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/220526_java_03
username=root
password=root


/**
 * jdbc的工具类
 */
public class JDBCUtilsPlus {

    private static String url = null;
    private static String username = null;
    private static String password = null;

    //四大参数需要最先执行,而且只执行一次就好了
    static {
        try {
            //创建Properties集合
            Properties properties = new Properties();
            //读取配置文件
            InputStream in = JDBCUtilsPlus.class.getClassLoader().getResourceAsStream("jdbc.properties");

            properties.load(in);

            String driverClass = properties.getProperty("driverClass");
            Class.forName(driverClass);

            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");

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

    }

    //定义方法,用来获取连接
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //关闭资源
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}



public class Test03 {
    @Test
    public void add()throws Exception{
        Connection connection = JDBCUtilsPlus.getConnection();
        String sql = "insert into user (username,password) values (?,?)";
        PreparedStatement pst = connection.prepareStatement(sql);
        pst.setObject(1,"tom");
        pst.setObject(2,"abc");
        pst.executeUpdate();
        JDBCUtilsPlus.close(connection,pst,null);
    }

    @Test
    public void delete()throws Exception{
        Connection connection = JDBCUtilsPlus.getConnection();
        String sql = "delete from user where uid = ?";
        PreparedStatement pst = connection.prepareStatement(sql);
        pst.setObject(1,"3");
        pst.executeUpdate();
        JDBCUtilsPlus.close(connection,pst,null);
    }

    @Test
    public void update()throws Exception{
        Connection connection = JDBCUtilsPlus.getConnection();
        String sql = "update user set username = ? where uid = ?";
        PreparedStatement pst = connection.prepareStatement(sql);
        pst.setObject(1,"金莲");
        pst.setObject(2,"7");
        pst.executeUpdate();
        JDBCUtilsPlus.close(connection,pst,null);
    }

    @Test
    public void find()throws Exception{
        Connection connection = JDBCUtilsPlus.getConnection();
        String sql = "select * from user";
        PreparedStatement pst = connection.prepareStatement(sql);
        ResultSet resultSet = pst.executeQuery();
        while(resultSet.next()){
            Object uid = resultSet.getObject("uid");
            Object username = resultSet.getObject("username");
            Object password = resultSet.getObject("password");

            System.out.println(uid+"..."+username+"..."+password);
        }
        JDBCUtilsPlus.close(connection,pst,resultSet);
    }
}


day04.连接池-DBUtils-事务

课前回顾:
 1.jdbc概述:操作数据库的一个技术,是一个标准
 2.开发步骤:
   a.注册驱动:
     Class.forName("Driver的类的全限定名")
   b.获取连接:
     DriverManager.getConnection("数据库url","mysql用户名","mysql密码")
   c.获取执行平台:
     createStatement()
   d.准备sql:写sql语句
   e.执行sql:
     int executeUpdate(sql)-> 针对增删改操作
     ResultSet executeQuery(sql)  ->针对查询,返回一个结果集 
   f.处理结果集:
     next()->判断结果集中有没有下一个数据
     getxxx()-> 获取结果集中的数据
   g.关闭资源:
     close()
 3.PreparedStatement:预处理对象,Statement中的子接口
   a.获取:
     connection.preparedStatement(sql)
   b.特点:sql语句支持占位符  ?
   c.?赋值
     setxxx(指定第几个?,?赋值)
   d.执行sql
     int executeUpdate()-> 针对增删改操作
     ResultSet executeQuery()  ->针对查询,返回一个结果集 
今日重点:
  1.会使用Druid(德鲁伊)连接池完成数据库开发
  2.会使用DBUtils数据库工具包
  3.会在代码中添加事务

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LfUtmyAG-1659014506278)(D:\Typora\bin\document\img\1656809001678.png)]

第一章.PreparedStatement预处理对象

CREATE TABLE category(
  cid INT PRIMARY KEY AUTO_INCREMENT,
  cname VARCHAR(10)
);

1.mysql批量添加数据

注意:

​ 1.在批量添加数据时,需要在配置文件后加上

?rewriteBatchedStatements=true

​ 2.需要在多条添加的循环里加上addBatch()通过执行平台对象调用

​ 3.执行SQL要使用executeBatch() 执行多个数据批量执行

driverClass=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/220526_java_04?rewriteBatchedStatements=true
username=root
password=root

1.在设置完所有要添加的参数,调用PreparedStatement中的addBatch(),将SQL语句添加到PreparedStatement2.调用PreparedStatement中的executeBatch()方法批处理sql语句

public class Test01 {
    @Test
    public void add()throws Exception{
        //1.获取连接
        Connection connection = JDBCUtils.getConnection();
        //2.写sql语句
        String sql = "insert into category (cname) values (?)";
        //3.创建执行平台
        PreparedStatement pst = connection.prepareStatement(sql);
        /*
           4.执行sql
             mysql默认情况下,会把多条要执行的sql拆开来一个一个的执行
             如果要是批处理,可以理解为将多条要执行的sql看成是一组操作,不拆分执行
         */

        for (int i = 0; i < 100; i++) {
            pst.setObject(1,"箱包"+i);

             /*
              void addBatch()
              将一组参数添加到此 PreparedStatement 对象的批处理命令中
             */
             pst.addBatch();
        }

         /*
          批量执行
          executeBatch() 将一批命令提交给数据库来执行,全部命令执行成功
         */
         pst.executeBatch();

         //关闭资源
        pst.close();
        connection.close();
    }
}


第二章.连接池

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m4vOmEbA-1659014506279)(D:\Typora\bin\document\img\1656810874952.png)]

1.问题:
  之前的jdbc操作,每执行一个操作,就要获取一条连接对象(Connection对象),用完还要销毁,这样会耗费内存资源
2.过程:
  池子创建之后,如果来了任务,池子中有连接对象,就直接用,用完还回去
  不用频繁的去创建连接对象,销毁连接对象
      
3.常用的:
  C3p0    Druid

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VauS58hV-1659014506280)(D:\Typora\bin\document\img\1656811180664.png)]

1.连接池之C3p0(扩展)

注意:c3p0的配置文件名必须为c3p0-config.xml

除了配置文件不同,其他和Druid在配置文件和测试类中书写大差不差

1.导入c3p0的jar包:
  c3p0-0.9.1.2.jar
2.在resources下面创建一个xml文件,文件名取名为:c3p0-config.xml -> 文件名不能错
3.配置信息:
<c3p0-config>
    <!-- 使用默认的配置读取连接池对象 -->
    <default-config>
        <!--  连接参数 -->
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/220526_java_04?rewriteBatchedStatements=true</property>
        <property name="user">root</property>
        <property name="password">root</property>

        <!--
          连接池参数
          初始连接数(initialPoolSize):刚创建好连接池的时候准备的连接数量
          最大连接数(maxPoolSize):连接池中最多可以放多少个连接
          最大等待时间(checkoutTimeout):连接池中没有连接时最长等待时间
          最大空闲回收时间(maxIdleTime):连接池中的空闲连接多久没有使用就会回收
         -->
        <property name="initialPoolSize">5</property>
        <property name="maxPoolSize">10</property>
        <property name="checkoutTimeout">2000</property>
        <property name="maxIdleTime">1000</property>
    </default-config>
</c3p0-config>

4.编写工具类:
  接口:DataSource
  c3p0连接池实现类:ComboPooledDataSrouce
  获取连接,是在连接池中获取:ComboPooledDataSrouce.getConnection()  

public class C3P0Utils {
    private static DataSource dataSource = null;
    static {
        try {
            //创建c3p0的实现类对象,赋值给DataSource
            
            //c3p0的实现类对象会自动解析xml配置文件,解析配置文件中的4大参数
            dataSource = new ComboPooledDataSource();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //定义方法,用来获取连接
    public static Connection getConnection() {
        Connection connection = null;
        try {
            //从连接池中获取连接对象
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //关闭资源
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}



public class Test01 {
    @Test
    public void add()throws Exception{
        //1.获取连接
        Connection connection = C3P0Utils.getConnection();
        //2.准备sql
        String sql = "insert into category (cname) values (?)";
        //3.获取执行平台
        PreparedStatement pst = connection.prepareStatement(sql);
        //4.为?赋值
        pst.setObject(1,"箱包");
        //5.执行sql
        pst.executeUpdate();
        //6.关闭资源
        C3P0Utils.close(connection,pst,null);
    }
}


2.连接池之Druid(德鲁伊)

注意:

在配置文件中url,username,password名字不能更改.

1.概述:是阿里巴巴开发的号称目前最稳定的连接池
2.使用:Druid连接池需要配合properties文件使用
  a.在resouces下面创建一个properties配置文件-> 取名为druid.properties  
  b.到jar包:druid-1.1.10.jar
  c.在properties文件中配置
    driver=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://localhost:3306/220227_java4
    username=root
    password=root
        
3.编写Druid的工具类:
  DruidDataSourceFactory.createDataSource(Properties集合);返回的是DataSource接口的实现类


public class DruidUtils {
    private static DataSource dataSource = null;
    static {
        try {
            //创建properties集合
            Properties properties = new Properties();
            //读取properties配置文件
            InputStream in = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(in);

            //创建Druid的连接池实现类
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //定义方法,用来获取连接
    public static Connection getConnection() {
        Connection connection = null;
        try {
            //从连接池中获取连接对象
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //关闭资源
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}



   public class Test01 {
    @Test
    public void add()throws Exception{
        //1.获取连接
        Connection connection = DruidUtils.getConnection();
        //2.准备sql
        String sql = "insert into category (cname) values (?)";
        //3.获取执行平台
        PreparedStatement pst = connection.prepareStatement(sql);
        //4.为?赋值
        pst.setObject(1,"服装");
        //5.执行sql
        pst.executeUpdate();
        //6.关闭资源
        DruidUtils.close(connection,pst,null);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

点份炸鸡778

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值