Batch:需要执行大量的数据时可以使用批处理
注意点:
1、尽量使用Statement,因为如果是PreParedStatement可能会因为数据量太大而存在空间问题,编译器会报错。
2、把自动提交关闭,设置为手动提交。
事务:
基本概念:是数据库操作的一个单元,是一组同时执行,要么同时成功要么同时失败的语句。
开始于:连接到数据库上,并执行一条DML语句,前一个事务结束后又有一条新的DML语句
结束于: 执行COMMIT或ROLLBACK语句
执行一条DDL语句,例如CREATE TABLE语句,在这种情况下会自动执行COMMIT语句
执行一条DCL语句,例如GRANT语句,在这种情况下会自动执行COMMIT语句
断开与数据库的连接
执行一条DDL语句失败,这个时候就会自动执行ROLLBACK。
事务的四大特点(ACID):
Atomicity(原子性):表示一个事务内所有的操作都是一个整体,要么同时成功,要么同时失败。
Consistency(一致性):一个事物内任何一条语句发生错误,整个状态回滚到修改前
ISOLATION(隔离性):事务查看数据时数据所处的状态要么是另一并发事务修改前的状态,要么是修改后的状态,不会查看中间状态。
DURABILITY(持久性):一旦commit那么对于数据库的影响是永久的。
事务隔离级别由低到高:
读取未提交
读取已提交
可重复度
序列化
CLOB:用于存储大量的文本数据,大字段一般是以流的方式读取的。
使用CLOB将文本写入数据库中:
Class.forName("com.mysql.jdbc.Driver");conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/kk_1", "root", "MySQL1998" );ps=conn.prepareStatement("insert into k_table (username,myInfo) values (?,?)");ps.setString(1,"赵大帅");//输入文件中的内容://ps.setClob(2,new FileReader(new File("E:\\a.txt")));//输入程序中的字符串,这里不能直接使用String,因为DLOB需要的是流ps.setClob(2,new BufferedReader(new InputStreamReader(new ByteArrayInputStream("zyk is beautiful".getBytes()))));ps.execute();System.out.println("OK");
在使用CLOB是出现异常:
Exception in thread "main" java.lang.AbstractMethodError: com.mysql.jdbc.PreparedStatement.isClosed
解决方法:更新connector包。
使用CLOB查询指定的数据:
import java.io.*;import java.sql.*;public class TestCLOB { public static void main(String[] args) { PreparedStatement ps=null; Connection conn=null; ResultSet rs=null; try { Class.forName("com.mysql.jdbc.Driver"); conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/kk_1", "root", "MySQL1998" );ps=conn.prepareStatement("select * from k_table where id=?");ps.setInt(1,60010);rs=ps.executeQuery();while(rs.next()){ Clob c=rs.getClob("myInfo"); Reader reader=c.getCharacterStream(); int temp=0; while((temp=reader.read())!=-1){ System.out.print((char) temp); }}System.out.println("OK");
BLOB:用于存储大量的二进制文件
try { Class.forName("com.mysql.jdbc.Driver"); conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/kk_1", "root", "MySQL1998" ); ps=conn.prepareStatement("insert into k_table (username,headImg) values (?,?)"); ps.setString(1,"赵大帅"); //存入blob ps.setBlob(2,new FileInputStream("e:/timg.jpg")); ps.execute();
取出BLOB信息:
public class TestCLOB { public static void main(String[] args) { PreparedStatement ps=null; Connection conn=null; ResultSet rs=null; //Reader reader=null; InputStream inputStreamReader=null; OutputStream outputStream=null; try { Class.forName("com.mysql.jdbc.Driver"); conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/kk_1", "root", "MySQL1998" ); //去除BLOB ps=conn.prepareStatement("select * from k_table where id=?"); ps.setInt(1,60011); rs=ps.executeQuery(); while(rs.next()){ Blob blob=rs.getBlob("headImg"); inputStreamReader=blob.getBinaryStream(); outputStream=new FileOutputStream("e:/aaa.jpg"); int temp=0; while((temp=inputStreamReader.read())!=-1){ outputStream.write(temp); } }