笔记
/*
1.LOB(Large Object,大型对象)类型的字段现在用得越来越多了。因为这种类型的字段,容量大(最多能容纳4GB的数据),且一个表中可以有多个这种类型的字段,很灵活,适用于数据量非常大的业务领域(如图象、档案等)。
2.LOB类型分为BLOB和CLOB两种:BLOB即二进制大型对象(Binary Large Object),适用于存贮非文本的字节流数据(如程序、图象、影音等)。
3.而CLOB,即字符型大型对象(Character Large Object),则与字符集相关,适于存贮文本型的数据(如历史档案、大部头著作等)。
4. 四种类型的最大长度: tinyBlob:255, Blob:65k, MediumBlob:16M, LongBlob:4G text也是这4种类型,长度类似
create table note{
id int,
note text;
}
字段定义成 "note varchar(100000)" 时,数据库自动会把它转成 MediumText类型
CREATE TABLE img(
id INT,
img BLOB //MEDIUMBLOB
);
*
*/
//※凡是要写入大数据字段,都只能使用PreparedStatement, 不能使用Statement。读取大数据字段是可以用Statement的。
package cn.bl.v2;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
import cn.bl.DBUtil;
public class LobDemo {
//测试blob - 保存
@Test
public void saveBlob() throws Exception {
Connection conn = DBUtil.getConnection();
String sql = " insert into img(image) values(?) ";
PreparedStatement pst = conn.prepareStatement(sql);
InputStream in = new FileInputStream(new File("E:/1.jpg"));
pst.setBinaryStream(1, in);
pst.execute();
conn.close();
}
//测试blob - 读取到硬盘
@Test
public void readBlob() throws Exception {
Connection conn = DBUtil.getConnection();
String sql = " select * from img ";
Statement st = conn.createStatement();
ResultSet set = st.executeQuery(sql);
while(set.next()) {
System.out.println(set.getInt("id"));
InputStream in = set.getBinaryStream("image");
OutputStream out = new FileOutputStream(new File("E:/2.jpg"));
int len = -1;
byte[]b = new byte[1024];
while((len=in.read(b))!=-1){
out.write(b, 0, len);
}
in.close();
out.close();
}
}
//测试clob
@Test
public void saveClob() throws Exception {//注意文本编码是utf-8的,要对应mysql的
Connection conn = DBUtil.getConnection();
String sql = " insert into note(note) values(?) ";
PreparedStatement pst = conn.prepareStatement(sql);
InputStream in = new FileInputStream(new File("E:/1.txt"));
pst.setAsciiStream(1, in);
pst.execute();
in.close();
conn.close();
}
@Test
public void readClob() throws Exception {
Connection conn = DBUtil.getConnection();
String sql = " select * from note where id = 1";
Statement st = conn.createStatement();
ResultSet set = st.executeQuery(sql);
while(set.next()) {
System.out.println(set.getInt(1));
InputStream in = set.getAsciiStream("note");
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
String string = "";
while((string = bin.readLine())!=null){
System.out.println(string);
}
in.close();
}
}
}