之前:一次操作只能发送一条sql语句到数据库服务器,效率并不高!
如果要插入2000条记录,那么必须发送2000条sql语句。
如果IO流的话,一次写出一个字节,显然效率效率并不高,所以可以使用缓存字节数组提高每次写出的效率。
现在:插入2000条记录,但现在使用sql缓存区,一次发送多条sql到数据库服务器执行。这种做法就叫做批处理。
Statement批处理:
void addBatch(String sql) 添加sql到缓存区(暂时不发送)
int[] executeBatch() 执行批处理命令。 发送所有缓存区的sql
void clearBatch() 清空sql缓存区
PreparedStatement批处理:
void addBatch() 添加参数到缓存区
int[] executeBatch() 执行批处理命令。 发送所有缓存区的sql
void clearBatch() 清空sql缓存区
案例:分别测试statement和preparedstatement使用和不使用批处理向学生表插入2000条数据的效率
public class Test {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
// testStatement();//67992
// testStatementBatch();//66272
// testPreparedStatement();//66194
testPreparedStatementBatch();//68663
long endTime = System.currentTimeMillis();
System.out.println(endTime-startTime);
}
private static void testPreparedStatementBatch() {
Connection conn = null;
PreparedStatement stmt = null;
try{
conn = JDBCUtil.getConn();
//创建一个动态的sql语句
String sql = "insert into student(id,name) values(?,?);";
stmt = conn.prepareStatement(sql);
//型数据库插入2000条数据,一次插入一条
for (int i = 1; i <=2000; i++) {
stmt.setInt(1, i);
stmt.setString(2, "Hins");
stmt.addBatch();
//判断每20条发送一次
if (i%20==0) {
stmt.executeBatch();
//清空缓存区
stmt.clearBatch();
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtil.close(conn, stmt, null);
}
}
private static void testPreparedStatement() {
Connection conn = null;
PreparedStatement stmt = null;
try{
conn = JDBCUtil.getConn();
//创建一个动态的sql语句
String sql = "insert into student(id,name) values(?,?);";
stmt = conn.prepareStatement(sql);
//型数据库插入2000条数据,一次插入一条
for (int i = 1; i <=2000; i++) {
stmt.setInt(1, i);
stmt.setString(2, "Hins");
//发送参数
stmt.executeUpdate();
}
}catch(Exception e){
e.printStackTrace();
}finally{
//释放资源
JDBCUtil.close(conn, stmt, null);
}
}
private static void testStatementBatch() {
Connection conn = null;
PreparedStatement stmt = null;
try{
conn = JDBCUtil.getConn();
String sql = "insert into student(id,name) values(?,?);";
stmt = conn.prepareStatement(sql);
//型数据库插入2000条数据,一次插入一条
for (int i = 1; i <=2000; i++) {
stmt.setInt(1, i);
stmt.setString(2, "hins");
stmt.addBatch();
//判断每20条发送一次
if (i%20==0) {
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 = 1; i < 2000; i++) {
String sql = "insert into student(id,name) values("+i+",'Hins')";
stmt.executeUpdate(sql);
}
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtil.close(conn, stmt, null);
}
}
}
prepareStatement(String sql, int autoGeneratedKeys)
PreparedStatement
对象,该对象能获取自动生成的键。
ResultSet getGeneratedKeys() throws SQLException
Statement
对象而创建的所有自动生成的键。如果此
Statement
对象没有生成任何键,则返回空的
ResultSet
对象。
public class IncrementDemo {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try{
conn = JDBCUtil.getConn();
String sql1 = "insert into dept(deptName) values(?)";
String sql2 = "insert into employee(name,deptId) values(?,?);";
stmt = conn.prepareStatement(sql1,Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, "财务部");
stmt.executeUpdate();
//获取自增长键
rs = stmt.getGeneratedKeys();
int deptId = 0;
while (rs.next()) {
deptId = rs.getInt(1);
}
//插入数据
stmt.setString(1, "Hins");
stmt.setInt(2, deptId);
stmt.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtil.close(conn, stmt, rs);
}
}
}
字符:
存储字符内容: 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
public class ClobDemo {
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 news ";
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while(rs.next()){
Reader reader = rs.getCharacterStream(2);
FileWriter fw = new FileWriter("D://a.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, rs);
}
}
private static void write() {
// TODO Auto-generated method stub
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("C://Users/Knight/Desktop/SQLyog_Enterprise/下载安装说明.txt"));
stmt.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
JDBCUtil.close(conn,stmt,null);
}
}
}
public class BlobDemo {
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 attachment where id=?;";
stmt = conn.prepareStatement(sql);
//给参数赋值
stmt.setInt(1, 1);
rs = stmt.executeQuery();
//遍历结果集
while (rs.next()) {
//读取第2个字段
InputStream is = rs.getBinaryStream(2);
FileOutputStream fos = new FileOutputStream("D://nm.jpg");
byte[] chs = new byte[1024];
int len;
while ((len=is.read(chs))!=-1) {
fos.write(chs, 0, len);
}
//释放资源
fos.close();
is.close();
}
}catch(Exception e){
e.printStackTrace();
}finally{
//释放资源
JDBCUtil.close(conn, stmt, rs);
}
}
private static void write() {
Connection conn = null;
PreparedStatement stmt = null;
try{
conn = JDBCUtil.getConn();
String sql = "insert into attachment values(?,?);";
//预编译sql
stmt = conn.prepareStatement(sql);
//给sql参数赋值
stmt.setInt(1, 2);
//数据库默认要求,写入文件的大小是1m,如果存入数据库的文件大于这个容量就会抛出异常
//com.mysql.jdbc.PacketTooBigException
//max_allowed_packet
stmt.setBlob(2, new FileInputStream("D://abc.mp3"));
//发送参数并执行sql
int count = stmt.executeUpdate();
System.out.println(count);
}catch(Exception e){
e.printStackTrace();
}finally{
//释放资源
JDBCUtil.close(conn, stmt, null);
}
}
}
所谓的事务,如果把多条sql语句看做一个事务,那么这个事务要么一起成功,要么一起失败!!
setautocommit =0 / 1;设置是否自动提交事务
1: 表示自动提交事务,每执行一条sql语句,自动提交事务。
0: 表示关闭自动提交事务。
commit; 提交事务,一旦提交事务不能回滚
rollback; 回滚事务。回滚到事务的起始点。
Connection.setAutoCommit(false) 开启事务
Connection.commit(); 成功执行,最后提交事务
Connection.rollback(); 一旦遇到错误,回滚事务
案例:模拟银行转账(转账失败时,扣钱这个步骤回滚)
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='马云';";
String addSql = "update account set balance=balance+2000 where name='Hins';";
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 (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}finally{
JDBCUtil.close(conn, stmt, null);
}
}
}
原子性: 要么一起成功过,要么一起失败
一致性: 数据库应该从一个一致性的状态到另一个一致性的状态,保持不变
隔离性: 多个并发事务直接应该可以相互隔离
持久性: 事务一旦提交,应该永久保持下来。