1 JDBC进行批处理
1.1 为什么要用批处理?
之前:一次操作只能发送一条sql语句到数据库服务器,效率并不高!
如果要插入2000条记录,那么必须发送2000条sql语句。如果IO流的话,一次写出一个字节,显然效率效率并不高,所以可以使用缓存字节数组提高每次写出的效率。
现在:插入2000条记录,但现在使用sql缓存区,一次发送多条sql到数据库服务器执行。这种做法就叫做批处理。
1.2 JDBC批处理的API
A. Statement批处理:void addBatch(String sql) 添加sql到缓存区(暂时不发送)
int[] executeBatch() 执行批处理命令。 发送所有缓存区的sql
void clearBatch() 清空sql缓存区
B. PreparedStatement批处理:
void addBatch() 添加参数到缓存区
int[] executeBatch() 执行批处理命令。 发送所有缓存区的sql
void clearBatch() 清空sql缓存区
案例:分别测试statement和preparedstatement使用和不使用批处理向学生表插入2000条数据的效率
package com.jdbc_statement_preparestatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import com.jdbc.util.JDBCUtil;
public class Test {
public static void main(String[] args) {
long startTime=System.currentTimeMillis();
//teststatement();//不使用批量处理,发送2000条数据
//teststatementBatch();//使用批量处理,发送2000条数据
testparaedstatement();
//testparaedstatementBatch();
long endTime=System.currentTimeMillis();
}
private static void testparaedstatementBatch() {
//创建连接对象
Connection conn=null;
PreparedStatement stmt=null;
try{
//获取连接对象
conn=JDBCUtil.getConn();
//创建动态sql语句
String sql="insert into student(id,name) values (?,?);";
conn.prepareStatement(sql);
stmt.addBatch();
//批量发送2000条数据
for(int i=0;i<2000;i++){
//设置
stmt.setInt(1, i);
stmt.setString(2, "小绿");
stmt.addBatch();
if(i%20==0){
stmt.executeBatch();
stmt.clearBatch();
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
//释放资源
JDBCUtil.close(conn, stmt, null);
}
}
private static void testparaedstatement() {
//创建连接对象
Connection conn=null;
PreparedStatement stmt=null;
try{
//获取连接对象
conn = JDBCUtil.getConn();
String sql="insert into student(id,name) values(?,?);";
stmt = conn.prepareStatement(sql);
for(int i=0;i<2000;i++){
//给?赋值
stmt.setInt(1, i);
stmt.setString(2, "刘德华");
stmt.executeUpdate();
}
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtil.close(conn, stmt, null);
}
}
private static void teststatementBatch() {
//创建连接对象
Connection conn =null;
Statement stmt =null;
try{
//获取连接
conn=JDBCUtil.getConn();
//创建语句执行对象
stmt=conn.createStatement();
//创建sql语句对象
for(int i=0;i<2000;i++){
String sql="insert into student(id,name) values("+i+",'吴亦凡');";
//把数据信息存储在batch数据块中
stmt.addBatch(sql);
if(i%20==0){
//批量发送SQL语句
stmt.executeBatch();
stmt.clearBatch();
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtil.close(conn, stmt, null);
}
}
private static void teststatement() {
//创建连接对象
Connection conn=null;
Statement stmt=null;
try{
//获取连接
conn=JDBCUtil.getConn();
//创建语句执行对象
stmt =conn.createStatement();
for(int i=0;i<2000;i++){
String sql="insert into student(id,name) values ("+i+",'刘德华';)";
stmt.execute(sql);
}
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtil.close(conn, stmt, null);
}
}
}
对于执行结果来说,块传送的速率并没有高多少,这里是因为mysql不支持数据缓存。
2 JDBC获取自增长值
package com.jdbc_statement_preparestatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import com.jdbc.util.JDBCUtil;
public class Test {
public static void main(String[] args) {
long startTime=System.currentTimeMillis();
//teststatement();//不使用批量处理,发送2000条数据
//teststatementBatch();//使用批量处理,发送2000条数据
testparaedstatement();
//testparaedstatementBatch();
long endTime=System.currentTimeMillis();
}
private static void testparaedstatementBatch() {
//创建连接对象
Connection conn=null;
PreparedStatement stmt=null;
try{
//获取连接对象
conn=JDBCUtil.getConn();
//创建动态sql语句
String sql="insert into student(id,name) values (?,?);";
conn.prepareStatement(sql);
stmt.addBatch();
//批量发送2000条数据
for(int i=0;i<2000;i++){
//设置
stmt.setInt(1, i);
stmt.setString(2, "小绿");
stmt.addBatch();
if(i%20==0){
stmt.executeBatch();
stmt.clearBatch();
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
//释放资源
JDBCUtil.close(conn, stmt, null);
}
}
private static void testparaedstatement() {
//创建连接对象
Connection conn=null;
PreparedStatement stmt=null;
try{
//获取连接对象
conn = JDBCUtil.getConn();
String sql="insert into student(id,name) values(?,?);";
stmt = conn.prepareStatement(sql);
for(int i=0;i<2000;i++){
//给?赋值
stmt.setInt(1, i);
stmt.setString(2, "刘德华");
stmt.executeUpdate();
}
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtil.close(conn, stmt, null);
}
}
private static void teststatementBatch() {
//创建连接对象
Connection conn =null;
Statement stmt =null;
try{
//获取连接
conn=JDBCUtil.getConn();
//创建语句执行对象
stmt=conn.createStatement();
//创建sql语句对象
for(int i=0;i<2000;i++){
String sql="insert into student(id,name) values("+i+",'吴亦凡');";
//把数据信息存储在batch数据块中
stmt.addBatch(sql);
if(i%20==0){
//批量发送SQL语句
stmt.executeBatch();
stmt.clearBatch();
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtil.close(conn, stmt, null);
}
}
private static void teststatement() {
//创建连接对象
Connection conn=null;
Statement stmt=null;
try{
//获取连接
conn=JDBCUtil.getConn();
//创建语句执行对象
stmt =conn.createStatement();
for(int i=0;i<2000;i++){
String sql="insert into student(id,name) values ("+i+",'刘德华';)";
stmt.execute(sql);
}
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtil.close(conn, stmt, null);
}
}
}
3 JDBC处理大数据文件
3.1 什么是大容量
字符:
存储字符内容: mysql: char(0-255) varchar(0-65535) 长度有限的。 65535
大容量的字符字段:
mysql: text(64K) longtext(4G字符内容)
oracle : clob longclob
字节:
mysql: blob(65kb) mediumblob(16mb) longblog(4GB)
oracle: blob
3.1 jdbc操作字符文件
package com.jdbc_clob;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.jdbc.util.JDBCUtil;
public class ClocDemo {
public static void main(String[] args) {
//需求:将一篇文章存储到数据库中
//write();
read();
}
private static void read() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try{
//获取连接
conn = JDBCUtil.getConn();
String sql = "select * from new ";
stmt = conn.prepareStatement(sql);
//执行sql
rs = stmt.executeQuery();
//便利结果集
while (rs.next()) {
//获取content字段的数据
Reader reader = rs.getCharacterStream(2);
//创建文件输出流对象
FileWriter fw = new FileWriter("D://url2.txt");
//边读边写
char[] chs = new char[1024];
int len;
while ((len=reader.read(chs))!=-1) {
fw.write(chs, 0, len);
//刷新
fw.flush();
}
//关流
fw.close();
reader.close();
}
}catch(Exception e){
e.printStackTrace();
}finally{
//释放资源
JDBCUtil.close(conn, stmt, null);
}
}
private static void write() {
Connection conn = null;
PreparedStatement stmt = null;
try{
conn = JDBCUtil.getConn();
String sql = "insert into news values(?,?);";
stmt = conn.prepareStatement(sql);
//给?参数
stmt.setString(1, "吴亦凡来了");
stmt.setClob(2, new FileReader("D://url.txt"));
//发送参数,并执行sql
int count = stmt.executeUpdate();
System.out.println(count);
}catch(Exception e){
e.printStackTrace();
}finally{
//释放资源
JDBCUtil.close(conn, stmt, null);
}
}
}
3.2 jdbc操作字节文件
package com.jdbc_clob;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.jdbc.util.JDBCUtil;
public class BlobDemo {
public static void main(String[] args) {
//write();//给数据库中存出一张图片
read();
}
private static void write() {
//创建连接对象
Connection conn=null;
PreparedStatement stmt=null;
try{
//创建连接对象
conn=JDBCUtil.getConn();
//创建sql语句
String sql="insert into student values(?,?)";
//预编译sql语句
conn.prepareStatement(sql);
//给sql参数赋值
stmt.setInt(1, 1);
stmt.setBlob(2, new FileInputStream("d://abc.apg"));
int count=stmt.executeUpdate();
System.out.println(count);
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtil.close(conn, stmt, null);
}
}
private static void read() {
//创建连接对象
Connection conn=null;
PreparedStatement stmt=null;
ResultSet rs=null;
try{
//获取连接对象
conn=JDBCUtil.getConn();
//创建Sql语句
String sql="select*from student where id=2";
stmt=conn.prepareStatement(sql);
//给参数赋值
stmt.setInt(1, 2);
rs=stmt.executeQuery();
//遍历结果集
while(rs.next()){
InputStream is = rs.getBinaryStream(3);
FileOutputStream fos=new FileOutputStream("d://abc.apg");
byte[] chs=new byte[1024];
int len;
while((len=is.read(chs))!=-1){
fos.write(chs, 0, len);
}
//释放资源
is.close();
fos.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: 表示关闭自动提交事务。
commit; 提交事务,一旦提交事务不能回滚
rollback; 回滚事务。回滚到事务的起始点。
4.3 jdbc事务操作
Connection.setAutoCommit(false) 开启事务
Connection.commit(); 成功执行,最后提交事务
Connection.rollback(); 一旦遇到错误,回滚事务
package com.jdbc_transation;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.jdbc.util.JDBCUtil;
public class TransationDemo {
public static void main(String[] args) {
//创建连接对象
Connection conn =null;
PreparedStatement stmt = null;
//创建动态sql语句
String delSql = "update account set balance=balance-2000 where name='james';";
String addSql = "update account set balance=balance+2000 where name='weide';";
try{
conn = JDBCUtil.getConn();
conn.setAutoCommit(false);//将自动提交设置为手动提交
stmt = conn.prepareStatement(delSql);
stmt.executeUpdate();
//int i = 1/0;//假设在这里抛出了一个异常
stmt =conn.prepareStatement(addSql);
stmt.executeUpdate();
//手动提交
conn.commit();
System.out.println("转账成功");
}catch(Exception e){
e.printStackTrace();
//回滚
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}finally{
//释放资源
JDBCUtil.close(conn, stmt, null);
}
}
}
4.4事务4大特性(面试中会被问到)
原子性: 要么一起成功过,要么一起失败
一致性: 数据库应该从一个一致性的状态到另一个一致性的状态,保持不变
隔离性: 多个并发事务直接应该可以相互隔离
持久性: 事务一旦提交,应该永久保持下来。