程序员的知识教程库

网站首页 > 教程分享 正文

JDBC加强(批处理和事务)(jdbc 批处理)

henian88 2024-10-14 10:02:59 教程分享 8 ℃ 0 评论

1、JDBC进行批处理

1.1 为什么要用批处理?

之前:一次操作只能发送一条sql语句到数据库服务器,效率并不高!

如果要插入2000条记录,那么必须发送2000条sql语句。

如果IO流的话,一次写出一个字节,显然效率效率并不高,所以可以使用缓存字节数组提高每次写出的效率。

现在:插入2000条记录,但现在使用sql缓存区,一次发送多条sql到数据库服务器执行。这种做法就叫做批处理。

1.2 JDBC批处理的API

Statement批处理:

void addBatch(String sql) 添加sql到缓存区(暂时不发送)

int[] executeBatch() 执行批处理命令。 发送所有缓存区的sql

void clearBatch() 清空sql缓存区

PreparedStatement批处理:

void addBatch() 添加参数到缓存区

int[] executeBatch() 执行批处理命令。 发送所有缓存区的sql

void clearBatch() 清空sql缓存区

2、JDBC获取自增长值

/**

* 获取自增长值

* @author APPle

*/

public class Demo1 {

@Test

public void test(){

//插入部门表数据

String deptSql = "INSERT INTO dept(deptName) VALUES(?)";

//插入员工表数据

String empSql = "INSERT INTO employee(empName,deptId) VALUES(?,?)";

Connection conn = null;

PreparedStatement stmt = null;

ResultSet rs = null;

try{

//获取连接

conn = JdbcUtil.getConnection();

/**

* 1)插入部门

*/

//预编译部门sql

//stmt = conn.prepareStatement(deptSql);

//

/**

* 1.1 使用两个参数的prepareStatement()方法,指定可以返回自动增长的键值

* Statement.RETURN_GENERATED_KEYS: 可以返回自动增长值

* Statement.NO_GENERATED_KEYS: 不能返回自动增长值

*/

stmt = conn.prepareStatement(deptSql, Statement.RETURN_GENERATED_KEYS);

//设置参数

stmt.setString(1, "秘书部");

//执行部门sql

stmt.executeUpdate();

/**

* 1.2 获取自增长的值

*/

rs = stmt.getGeneratedKeys();

Integer deptId = null;

if(rs.next()){

deptId = rs.getInt(1);//得到第一行第一列的值

}

/**

* 2)插入员工,员工在刚添加的部门中

*/

stmt = conn.prepareStatement(empSql);

//设置参数

stmt.setString(1, "李四");

stmt.setInt(2, deptId); //如何获取刚刚添加的部门ID??

//执行员工sql

stmt.executeUpdate();

}catch(Exception e){

e.printStackTrace();

}finally{

JdbcUtil.close(conn, stmt, rs);

}

}

}


3、JDBC处理大数据文件

mysql:

字符串: varchar char 65535

大文本数据: tinytext , longtext ,text

字节: bit

大字节文件: tinyblob(255byte), blob(64kb),MEDIUMBLOB(约16M) longblob(4GB)

oracle:

字符串: varchar2 char 65535

大文本数据: clob

字节: bit

大字节文件: blob

3.1 jdbc操作字符文件

/**

* 对大文本数据处理

* @author APPle

*/

public class Demo1 {

/**

* 文件保存到数据中

*/

@Test

public void testWrite(){

Connection conn = null;

PreparedStatement stmt = null;

try{

//获取连接

conn = JdbcUtil.getConnection();

//创建PreparedStatement

String sql = "INSERT INTO test1(content) VALUES(?)";

stmt =conn.prepareStatement(sql);

//设置参数

/**

* 参数一: 参数位置

* 参数二: 输入字符流

*/

/**

* 读取本地文件,返回输入字符流

*/

FileReader reader = new FileReader(new File("e:/Demo1.java"));

stmt.setClob(1, reader);

//执行sql

int count = stmt.executeUpdate();

System.out.println("影响了"+count+"行");

}catch(Exception e){

e.printStackTrace();

}finally{

JdbcUtil.close(conn, stmt, null);

}

}

/**

* 从数据中读取文本内容

*/

@Test

public void testRead(){

Connection conn = null;

PreparedStatement stmt = null;

ResultSet rs = null;

try{

//获取连接

conn = JdbcUtil.getConnection();

String sql = "SELECT * FROM test1 where id=?";

stmt = conn.prepareStatement(sql);

//设置参数

stmt.setInt(1, 2);

//执行sql,返回结果集

rs = stmt.executeQuery();

if(rs.next()){

//方式一:当做字符串取出数据

/*

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

System.out.println(content);

*/

//方式二:返回输入流形式

Clob clob = rs.getClob("content");

Reader reader = clob.getCharacterStream();

//写出到文件中

FileWriter writer = new FileWriter(new File("e:/Demo2.java"));

char[] buf = new char[1024];

int len = 0;

while( (len=reader.read(buf))!=-1){

writer.write(buf, 0, len);

}

//关闭流

writer.close();

reader.close();

}

}catch(Exception e){

e.printStackTrace();

}finally{

JdbcUtil.close(conn, stmt, rs);

}

}

}


3.2 jdbc操作字节文件

/**

* 对字节文件处理

* @author APPle

*/

public class Demo2 {

/**

* 文件保存到数据库中

*/

@Test

public void testWrite(){

Connection conn = null;

PreparedStatement stmt = null;

try{

//获取连接

conn = JdbcUtil.getConnection();

String sql = "insert into test2(content) values(?)";

stmt = conn.prepareStatement(sql);

//设置参数

/**

* 参数一:参数位置

* 参数二:输入字节流

*/

/**

* 读取本地文件

*/

InputStream in = new FileInputStream(new File("e:/abc.wmv"));

//stmt.setBlob(1, in);

stmt.setBinaryStream(1, in);

//执行

stmt.executeUpdate();

}catch(Exception e){

e.printStackTrace();

}finally{

JdbcUtil.close(conn, stmt, null);

}

}

/**

* 注意: mysql数据库默认情况下,只能存储不超过1m的文件,由于max_allowed_packet变量的限制

* 可以修改: %mysql%/my.ini文件, 修改或添加max_allowed_packet变量,然后重启mysql即可!!

*/

/**

* 从数据中读取字节内容

*/

@Test

public void testRead(){

Connection conn = null;

PreparedStatement stmt = null;

ResultSet rs = null;

try{

//获取连接

conn = JdbcUtil.getConnection();

String sql = "SELECT * FROM test2 where id=?";

//获取PreparedStatement

stmt = conn.prepareStatement(sql);

//设置参数

stmt.setInt(1, 1);

//执行sql

rs = stmt.executeQuery();

if(rs.next()){

//返回输入流

//InputStream in = rs.getBinaryStream("content");

InputStream in = rs.getBlob("content").getBinaryStream();

//写出文件中

FileOutputStream out = new FileOutputStream(new File("e://3.jpg"));

byte[] buf = new byte[1024];

int len = 0;

while((len=in.read(buf))!=-1){

out.write(buf, 0, len);

}

//关闭流

out.close();

in.close();

}

}catch(Exception e){

e.printStackTrace();

}finally{

JdbcUtil.close(conn, stmt, rs);

}

}

}


4、数据库事务

4.1 什么是事务?

所谓的事务,如果把多条sql语句看做一个事务,那么这个事务要么一起成功,要么一起失败!!

4.2 mysql事务操作命令

set autocommit =0 / 1; 设置是否自动提交事务

1: 表示自动提交事务,每执行一条sql语句,自动提交事务。

0: 表示关闭自动提交事务。

start transaction; 开启事务

commit; 提交事务,一旦提交事务不能回滚

rollback; 回滚事务。回滚到事务的起始点。

4.3 jdbc事务操作

Connection.setAutoCommit(false) 开启事务

Connection.commit(); 成功执行,最后提交事务

Connection.rollback(); 一旦遇到错误,回滚事务

/**

* 模拟银行转账

* @author APPle

*/

public class Demo1 {

/**

* 从eric的账户转2000元到rose的账户上

*/

@Test

public void testTransfer(){

//从eric账户上扣除2000元

String delSql = "UPDATE account SET BALANCE=BALANCE-2000 WHERE NAME='eric'";

//向rose账户打入2000元

String addSql = "UPDATE account SET BALANCE=BALANCE+2000 WHERE NAME='rose'";

Connection conn = null;

PreparedStatement stmt = null;

try{

//获取连接

conn = JdbcUtil.getConnection();

//开启事务

conn.setAutoCommit(false); // 等价于set autocommit=0;

//预编译delSQL

stmt = conn.prepareStatement(delSql);

//执行delSQL

stmt.executeUpdate();

//发生异常

int i = 100/0;

//预编译addSql

stmt = conn.prepareStatement(addSql);

//执行addSql

stmt.executeUpdate();

//提交事务

conn.commit();// 等价于commit;

}catch(Exception e){

e.printStackTrace();

//回滚事务

try {

conn.rollback(); // 等价于rollback;

} catch (SQLException e1) {

e1.printStackTrace();

}

}finally{

JdbcUtil.close(conn, stmt, null);

}

}

}


4.4 事务4大特性

原子性: 要么一起成功过,要么一起失败

一致性: 数据库应该从一个一致性的状态到另一个一致性的状态,保持不变

隔离性: 多个并发事务直接应该可以相互隔离

事务级别 脏读 不可重复读 幻读

read uncommitted: 否 否 否

read committed : 是 否 否

repeatable read: 是 是 否

serializable: 是 是 是

结论: 隔离性越高,数据库的性能越差。

持久性: 事务一旦提交,应该永久保持下来。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表