JDBC学习笔记(5) --批处理+插入获取自增长+事务编程

一.批处理sql语句

1.addBatch(String sql):添加批处理
2. executeBatch():执行批处理
3.clearBatch():清空批处理
package com.huan.statemennt;

import com.huan.dao.Dao;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;

/**
 * Created by pc on 17-5-1.
 */
public class Dml_Demo {

    String user ="root";
    String password = "root";
    String url = "jdbc:mysql://localhost:3306/eurasia_echarts?characterEncoding=UTF-8";
     Connection conn = null;
    PreparedStatement pstmt = null;
    @Test
    public void test() throws Exception{
        conn =Dao.getDao();

        //插入数据
        String sql = " insert into mahuan (name,age) values(?,?); ";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1,"aaa");
        pstmt.setInt(2,22);
        pstmt.addBatch();    //添加一次预定义参数
        pstmt.setString(1, "ccc");
        pstmt.setInt(2, 45);
        pstmt.addBatch();    //再添加一次预定义参数
        //批量执行预定义SQL
        pstmt.executeBatch();
       Dao.close(pstmt,conn);
    }
}

二.插入获取自增长

如何获取?
1.在参数中制定返回自增长列
    `pstmt = conn.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);`
2.在执行更新后,获取自增长列
    `ResultSet rs = pstmt.getGeneratedKeys();`

案例:

package com.huan.auto;

import com.huan.dao.Dao;
import org.junit.Test;

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

/**
 * Created by pc on 17-5-3.
 */
public class Demo {
    Connection conn = null;
    PreparedStatement pstmt = null;

    //普通插入没有获取自增长
    @Test
    public void testAutoIncrement() throws Exception {
        String sql = " insert into mahuan (name,age) values(?,?); ";
        conn = Dao.getDao();
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1,"huan");
        pstmt.setInt(2,22);
        pstmt.executeUpdate();

        Dao.close(pstmt,conn);
    }
    //插入获取自增长
    @Test
    public void testAutoIncrement1() throws Exception {
        String sql = " insert into mahuan (name,age) values(?,?); ";
        conn = Dao.getDao();
        //在参数中制定返回自增长列
        pstmt = conn.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
        pstmt.setString(1, "sansan");
        pstmt.setInt(2, 55);
        pstmt.executeUpdate();
        //在执行更新后,获取自增长列
        ResultSet rs = pstmt.getGeneratedKeys();
        while(rs.next()){
            System.out.println(rs.getInt(1));
        }
        Dao.close(rs,pstmt, conn);
    }
}

JDBC学习笔记(5) --批处理+插入获取自增长+事务编程_第1张图片

三.事务编程

事务是指一组最小的逻辑操作单元,里面有多个操作组成。组成事务的每一部分都要同时提交成功,否则一旦操作失败,整个操作会回滚
1.事务的ACID特性:

1.原子行(Atomicitu):原子行是指食物是一个不可分割的整体,事务中要么全部都发生,要么不发生。
2.一致性(Consistency):事务必须使数据库从一个一致性状态转换到另一个一致性的状态。
3.隔离性(Lsolation):当并发访问数据库时,数据库会为每一个访问者提供一个事务,各事务之间时没有关联的。
4.持久性(Durability):持久性是指一旦事务被提交,他对数据库中数据的改变就是永久性的。

2.方法:
1.void setAutoCommit (boolean autoCommit):设置事务是否自动提交,如果设置为false,表示手动提交事务
2. void commit():手动提交事务
3.void rollback():回滚,当出现异常时,所有已执行成功的代码需要回退到事务开始前状态。
4.Sacepoint setSavepoint(String name):回滚到指定位置

手动设置事务

package com.huan.test;

import com.huan.dao.Dao;

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

/**
 * Created by pc on 17-5-3.
 */
public class AccountDao {
    private Connection conn;
    private PreparedStatement pstmt;

    //转账使用事务
    public void trans()  {
        try {
            //设置事物为手动提交
            conn.setAutoCommit(false);
            String sql_zz = " update account set money=money-100 where accountname='mahuan'; ";
            String sql_sz = " update account set money=money+100 where accountname='xiaoming'; ";
            conn = Dao.getDao();
            pstmt = conn.prepareStatement(sql_zz);
            pstmt.executeUpdate();
            System.out.println("转账成功");

            pstmt = conn.prepareStatement(sql_sz);
            pstmt.executeUpdate();
            System.out.println("收账成功");


        }catch (Exception e){
            try {
                //出现异常回滚
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally {
            try {
                //提交
                conn.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            Dao.close(pstmt,conn);
        }
    }
}

指定回滚位置
package com.huan.test;

import com.huan.dao.Dao;

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

/**
 * Created by pc on 17-5-3.
 */
public class AccountDao {
    private Connection conn;
    private PreparedStatement pstmt;

    //转账使用事务
    public void trans()  {
        try {
            //设置事物为手动提交
            conn.setAutoCommit(false);
            //第一次转账
            String sql_zz = " update account set money=money-100 where accountname='mahuan'; ";
            String sql_sz = " update account set money=money+100 where accountname='xiaoming'; ";

            SavePoint sp = conn.setSavepoint();//回滚位置

            //第二次转账
            String sql_zz = " update account set money=money-200 where accountname='mahuan'; ";
            String sql_sz = " update account set money=money+200 where accountname='xiaoming'; ";
            conn = Dao.getDao();
            pstmt = conn.prepareStatement(sql_zz);
            pstmt.executeUpdate();
            System.out.println("转账成功");

            pstmt = conn.prepareStatement(sql_sz);
            pstmt.executeUpdate();
            System.out.println("收账成功");


        }catch (Exception e){
            try {
                //出现异常回滚到指定代码块
                conn.rollback(sp);
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally {
            try {
                //提交
                conn.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            Dao.close(pstmt,conn);
        }
    }
}

文章文集:JavaEE--学习笔记

你可能感兴趣的:(JDBC学习笔记(5) --批处理+插入获取自增长+事务编程)