java之JDBC事务管理和数据库连接池

8 篇文章 0 订阅
2 篇文章 0 订阅

目录

JDBC事务管理

数据库连接池

 XML配置文件中的参数测试

 Druid数据库连接池

 Druid工具类,以及测试

JDBCTemplate

练习


JDBC事务管理

概述:

1、事务:一个包含多个步骤的业务操作。如果这个业务操作被事务管理,则这多个步骤要么同时成功,要么同时失败。

2、操作:

1、开启事务

2、提交事务

3、回滚事务

3、使用Connection对象来管理事务

开启事务:setAutocommit(boolean autoCommit):调用该方法设置参数为false,即开启事务

在执行sql之前开启事务

提交事务:commit()

当所有sql都执行完提交事务

回滚事务:rollback()

在catch中回滚事务

 

代码示例:

public class jdbcDemo10 {

/*

  * 事务操作

 *

 * */

 public static void main(String[] args) {

        Connection conn=null;

        PreparedStatement pstm1=null;

        PreparedStatement pstm2=null;

        ResultSet rs=null;

        try {

        //1、获取连接

            conn=JDBCUtils.getConnection();

            //开启事务

            conn.setAutoCommit(false);

        //2、定义sql

        //2.1、张三-500

            String sql="update account set  balance =balance-? where id=?";

        //2.2、李四+500

            String sql2="update account set  balance =balance+? where id=?";

        //3、获取执行sql对象

            pstm1=conn.prepareStatement(sql);

            pstm2=conn.prepareStatement(sql2);

        //4、设置参数

        pstm1.setDouble(1,500);

        pstm1.setInt(2,1);

        pstm2.setDouble(1,500);

        pstm2.setInt(2,2);

        //5、执行sql

        pstm1.executeUpdate();

        //手动制造异常

            int i=3/0;

            //导致了程序执行了一半只扣了张三的钱

            // 解决办法使用事务

        pstm2.executeUpdate();

        conn.commit();

        //出现任何异常都回滚所以异常抓大一点的Exception

        } catch (Exception e) {

            //事务回滚

            try {

                if (conn!=null)

                conn.rollback();

            } catch (SQLException e1) {

                e1.printStackTrace();

            }

            e.printStackTrace();

        }finally {//资源回收

            JDBCUtils.close(pstm1,conn);

            JDBCUtils.close(pstm2,null);

        }

    }

}

 

说明:在没有用事务之前,在手动添加异常后张三-500但是李四没有+500

在使用事务后以要么sql都成功要么都失败的原则出现手动添加的异常后数据并没有变化

效果:

原数据:

进行交易后:出现异常

数据并未变化

数据库连接池

1、概念:就是一个容器(集合),存放数据库连接的容器。

当系统初始化好后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库时,从容器中获取连接对象,用户访问完之后,会将连接对象归还给容器。

 

2、好处:

1、节约资源

2、用户访问高效

 

 

3、实现:

1、标准接口DataSourc  javax.sql包下的

1、方法:

获取连接:getConnection()

归还连接:如果连接对象Connection是从连接池中获取的,那么调用Connection.close()方法则不会再关闭连接了。而是归还连接。

2、一般我们不去实现它,由数据库厂商来实现

1、C3P0:数据库连接池技术(比较老)

2、Druid:数据库连接池实现技术,由阿里巴巴提供

4、C3P0:数据库连接池技术

步骤:

1、导入jar包c3p0-0.9.5.2.jar和mchange-commons-java-0.2.12.jar,不要忘记导入数据库驱动jar包

2、定义配置文件:

名称:c3p0.properties 或者 c3p0-config.xml

路径:直接将文件放在src目录下

注意xml中&要转义成&

3、创建核心对象——数据库连接对象comboPooledDataSource

4、获取连接:getConnection

 

连接测试:

/*

* c3p0的演示

* */

public class C3P0Demo1 {

    public static void main(String[] args) throws SQLException {

        //1、创建数据库连接池对象

        DataSource ds =new ComboPooledDataSource();

        //2、获取连接对象

        Connection conn=ds.getConnection();

        //3、打印

        System.out.println(conn);

    }

}

效果:

 XML配置文件中的参数测试

 

/*

* xml中的参数验证测试

* */

public class C3P0Demo2 {

    public static void main(String[] args) throws SQLException {

       /* //1、获取DataSource,使用默认配置

        DataSource ds=new ComboPooledDataSource();

        //2、获取连接

        //验证最大连接数

        for (int i=1;i<=11;i++){

            Connection conn=ds.getConnection();

            System.out.println(i+":"+conn);

            if (i==5)

                //验证.close归还连接

                conn.close();//归还连接到连接池中

        }*/

        testNameConfig();//调用指定名称配置的函数

    }

    public static void testNameConfig() throws SQLException {

        //11获取指定名称的配置

        DataSource ds=new ComboPooledDataSource("otherc3p0");

        //2、获取连接

        for(int i=1;i<=10;i++)

        {

            Connection conn=ds.getConnection();

            System.out.println(i+":"+conn);

        }

    }

说明:

指定名称的参数中最大连接数是8,超过数量申请会报错

 

xml:
<c3p0-config>
  <!-- 使用默认的配置读取连接池对象 -->
  <default-config>
  	<!--  连接参数 -->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/db4?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT%2B8</property>
    <property name="user">root</property>
    <property name="password">******</property>
    
    <!-- 连接池参数 -->
    <!--初始化申请的连接数量-->
    <property name="initialPoolSize">5</property>
    <!--最大连接数量-->
    <property name="maxPoolSize">10</property>
    <!--超时时间3s-->
    <property name="checkoutTimeout">3000</property>
  </default-config>
  <!--传参name指定的配置-->
  <named-config name="otherc3p0"> 
    <!--  连接参数 -->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/db4?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT%2B8</property>
    <property name="user">root</property>
    <property name="password">*******</property>
    
    <!-- 连接池参数 -->
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">8</property>
    <property name="checkoutTimeout">1000</property>
  </named-config>
</c3p0-config>

 Druid数据库连接池

1、步骤:

1、导入jar包druid-1.0.9.jar

2、定义配置文件:

特点:是properties形式,名称任意,可以放在任意的目录下

3、加载配置文件——properties

4、获取数据库连接池对象:通过工厂类来过去 DruidDataSourceFactory

5、获取连接:getConnection

2、定义工具类

1、定义一个类JDBCUtils

2、提供静态代码块加载配置文件,初始化连接池对象

3、提供方法:

1、获取连接方法:通过数据库连接池获取

2、释放资源

3、获取连接池的方法

 

演示:

/*

* Druid 演示

* */

public class DruidDemo {

    public static void main(String[] args) throws Exception {

        //1、导入jar

        //2、定义配置文件

        //3、加载配置文件

        Properties pro=new Properties();

        InputStream is= DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");

        pro.load(is);

        //4、获取连接池对象

        DataSource ds= DruidDataSourceFactory.createDataSource(pro);

        //5、获取连接

        Connection conn=ds.getConnection();

        System.out.println(conn);

    }

}

 

druid.properties配置

driverClassName=com.mysql.cj.jdbc.Driver

url=jdbc:mysql://localhost:3306/db4?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8

username=root

password=*******

#初始化连接数量

initialSize=5

#最大连接数

maxActive=10

#最大等待时间

maxWait=3000

 Druid工具类,以及测试

/*
* Druid连接池工具类
* */
public class JDBCUtils {
    //1、定义成员变量DataSource
    private static DataSource ds;
    static {
        //加载配置文件
        Properties pro =new Properties();
        try {
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //2、获取DataSource
            ds= DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
    * 获取连接
    * */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    /*
    * 释放资源
    * */
    public static void  close(Statement stmt,Connection conn ){
       /* if (stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();//归还连接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }*/
        //简单写法
        close(null,stmt,conn);
    }
    public static void  close(ResultSet rs, Statement stmt, Connection conn ){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();//归还连接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    /*
    * 获取连接池方法
    * */
    public static DataSource getDataSource(){
        return ds;
    }
}
工具类测试:
/*
* 使用新的工具类
* */
public class DruidDemo2 {
    public static void main(String[] args) {
        Connection conn=null;
        PreparedStatement pstmt=null;
        /*
        * 完成一个添加的操作:给account表添加一条记录
        * */
        //1、获取连接
        try {
            conn= JDBCUtils.getConnection();
            //2、定义sql
            String sql="insert into account values(null,?,?)";
            //3、获取pstmt对象
            pstmt=conn.prepareStatement(sql);
            //4、给问号赋值
            pstmt.setString(1,"王五");
            pstmt.setDouble(2,3000);
            //5、执行sql
            int count=pstmt.executeUpdate();
            System.out.println(count);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(pstmt,conn);
        }
    }
}

效果:

 

JDBCTemplate

 

介绍:Spring框架对JDBC的简单封装,提供了一个JDBCTemplate对象简化JDBC的开发

步骤:

1、导入jar包

2、创建jdbcTemplate对象。依赖于数据源DataSource

*JdbcTemplate template=new JdbcTemplate(ds);

3、调用JdbcTemplate的方法来完成CRUD的操作

update():执行DML语句,增删改

queryForMap():查询结果将结果集封装为map集合,将列名作为key,值作为value 将这条记录封装为一个map集合

注意:这个方法查询的结果集长度只能是1

queryForList():查询结果将结果封装为List集合

注意:将每一条记录封装为一个Map集合,再将Map集合装载到List集合中

query():查询结果,将结果封装为JavaBean

query的参数:RowMapper。可以完成数据到javaBean的自动封装

用法:

List<Emp> list = template.query(sql, new BeanPropertyRowMapper<类型>(类型.class));

queryForObject:查询结果,将结果封装为对象

一般用于聚合函数的查询

 

 

 

 

演示:

/*

* JdbcTemplate入门

* */

public class jdbcTemplateDemo1 {

    public static void main(String[] args) {

        //1、导入jar

        //2、创建JDBCTemplate对象

        JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());

        //3、调用方法

        String sql="update account set balance=5000 where id=?";

        int count= template.update(sql,4);

        System.out.println(count);

    }

}

效果:

练习

idea中使用@Test的问题:

在Modules中导入idea文件夹中lib中的以下两个jar包

即可

 

package test.datasource.jdbctemplate;

import org.junit.Test;

import org.springframework.jdbc.core.BeanPropertyRowMapper;

import org.springframework.jdbc.core.JdbcTemplate;

import test.datasource.Emp;

import test.datasource.utils.JDBCUtils;

 

import java.util.List;

import java.util.Map;

 

/*

* 需求:

* 1、修改1号的数据为salary为10000

* 2、添加一条记录

* 3、删除刚才添加的记录

* 4、查询id为1的记录,将其封装为Map集合

* 5、查询所有记录,将其封装为List

* 6、查询所有记录,将其封装为Emp对象的List集合

* 7、查询总记录数

* */

public class jdbcTemplateDemo2 {

    //1、获取JDBCTemplate对象

    private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());

    //Junit单元测试,可以让方法独立执行

    //需求11、修改1号的数据为salary10000

    @Test

    public void  test1(){

        //2、定义sql

        String sql="update emp set salary=10000 where id =1001";

        //3、执行sql

        int count=template.update(sql);

        System.out.println(count);

    }

 

 

    //需求22、添加一条记录

    @Test

    public void test2(){

        String sql="insert  into emp(id,ename,dept_id) values (?,?,?)";

        int count= template.update(sql,1015,"郭靖",10);

        System.out.println(count);

    }

 

    //需求33、删除刚才添加的记录

    @Test

    public void  test3(){

        String sql="delete from emp where id=1015";

        int count=template.update(sql);

        System.out.println(count);

    }

 

    //需求44、查询id1的记录,将其封装为Map集合

    @Test

    public void test4(){

        String sql="select * from emp where id=?";

        //注意,这个方法查询的结果集长度只能是1

        Map<String,Object>map=template.queryForMap(sql,1001);

        System.out.println(map);

        //{id=1001, ename=孙悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20}

    }

 

    //需求55、查询所有记录,将其封装为List

    @Test

    public void test5(){

        String sql="select * from emp";

        final List<Map<String, Object>> list = template.queryForList(sql);

        for (Map<String, Object> stringObjectMap : list) {

            System.out.println(stringObjectMap);

        }

    }

 

    //需求66、查询所有记录,将其封装为Emp对象的List集合

    @Test

    public void test6(){

        String sql="select * from emp";

/*        //匿名内部类

        List<Emp> list= template.query(sql, new RowMapper<Emp>() {

            @Override

            public Emp mapRow(ResultSet rs, int i) throws SQLException {

                Emp emp=new Emp();

                int id=rs.getInt("id");

                String ename=rs.getString("ename");

                int job_id=rs.getInt("job_id");

                int mgr= rs.getInt("mgr");

                Date joindate = rs.getDate("joindate");

                double salary = rs.getDouble("salary");

                double bonus = rs.getDouble("bonus");

                int dept_id = rs.getInt("dept_id");

                emp.setId(id);

                emp.setEname(ename);

                emp.setJob_id(job_id);

                emp.setMgr(mgr);

                emp.setJoindate(joindate);

                emp.setSalary(salary);

                emp.setBonus(bonus);

                emp.setDep_id(dept_id);

                return emp;

            }

        });

        for (Emp emp : list) {

            System.out.println(emp);

        }*/

        List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));

        for (Emp emp : list) {

            System.out.println(emp);

        }

    }

 

    //需求77、查询总记录数

    @Test

    public void test7(){

        String sql="select count(id) from emp";//count返回long类型数据

        Long total = template.queryForObject(sql, Long.class);//第二个参数是返回结果的类型Long的字节码文件

        System.out.println(total);

    }

    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值