本篇文章知识点
1.向数据库写入文本大数据文件
2.读取数据库的文本大数据文件
3..向数据库写入二进制大数据文件
4.读取数据库的二进制大数据文件
为了演示,先在MySQL创建两个表用于读取/写入大数据文件
演示大数据对象所用数据库表的脚本:
CREATE TABLE note(
id INT PRIMARY KEY,
note TEXT //能保存65535个字符
);
CREATE TABLE img(
id INT PRIMARY KEY,
img MediumBLOB
);
TinyBLOB最大支持255B, BLOB最大只支持65K, MediumBLOB最大只支持16M, LongBLOB最大支持4G
另外一个小的知识点
CLOB: Character Large Object 最大上限就是4G
1) 有4种TEXT类型:TINYTEXT、TEXT、MEDIUMTEXT和LONGTEXT。这些对应4种BLOB类型
2) BLOB是一个二进制大对象,可以容纳可变数量的数据。有4种BLOB类型:TINYBLOB、BLOB、MEDIUMBLOB和LONGBLOB。它们只是可容纳值的最大长度不同。
首先必须要理解,向数据库写入或者读取大数据文件,肯定不能和普通的char、int等基本数据一样。直接写入。因为内存不够。所以要通过流!!!
向数据库写入文本大数据文件:setAsciiStream
@Test//保存大文本数据对象到数据库
public void demo1() throws Exception{
Connection con = ConnUtils.getConnection();
String sql = "insert into note values(?,?)";
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(1, 1);
InputStream in = new FileInputStream( new File("src/Studying/d15/ConnUtils.java"));
pst.setAsciiStream(2, in);
pst.executeUpdate();
con.close();
}
在数据库可以看到刚刚写入的文本数据
从数据库中读取文本大数据文件:getAsciiStream
@Test//读取大文本数据对象到数据库
public void demo3() throws Exception{
Connection con = ConnUtils.getConnection();
String sql = "select * from note where id = 1";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
rs.next();
InputStream in = rs.getAsciiStream(2);
BufferedReader br = new BufferedReader( new InputStreamReader(in));
String str = null;
while( (str=br.readLine())!=null){
System.out.println(str);
}
con.close();
}
向数据库写入二进制大数据文件
需要注意的是,数据库表设计的时候,对于二进制数据类型设计 有不同的大小的
TinyBLOB最大支持255B, BLOB最大只支持65K, MediumBLOB最大只支持16M, LongBLOB最大支持4G
}
@Test//保存二进制数据对象到数据库
public void demo2() throws Exception{
Connection con = ConnUtils.getConnection();
String sql = "insert into img values(?,?)";
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(1, 1);
InputStream in = new FileInputStream( new File("src/a.jpg"));
pst.setBinaryStream(2, in);
pst.executeUpdate();
con.close();
}
第一遍我存失败了
因为我的图片太大了。我修改了表的类型就成功了
4.读取数据库的二进制大数据文件
一开始我存的d:a/
“`
@Test//从数据库读取二进制文件
public void demo4() throws Exception{
Connection con = ConnUtils.getConnection();
String sql = “select * from img where id = 1”;
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
rs.next();
InputStream in = rs.getAsciiStream(2);
OutputStream out = new FileOutputStream("D:/a/a.png");
byte buf[] = new byte[512];
int len=0;
while( (len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
in.close();
out.close();
con.close();
}
“`