一、文本
首先建一个表
create table note(
id int,
note text
);
关于这个存放文本的note字段,有很多数据类型表示其大小,如下:
最大为4G,text支持65536个字节
在sqlyog中显示表,点击相应字段部分如下:
点进去后如下直观的操作即可:
图中是我已经导入好的文档了。
接下来就是java部分了
读:
@Test //读取大文件字段
public void readLob() throws Exception{
Connection con=ConnectionFactory.getConnection();
String sql="select * from note where id=1";
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(sql);
if (rs.next()){
InputStream in=rs.getAsciiStream(2);//读取大文本字段
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String line="";
while ((line=br.readLine())!=null){
System.out.println(line);
}
}
con.close();
}
写:(这里的写我就是直接指定了哪个文件了,
实际上应该要可以选择文件的,这里省略了)
@Test //写大文件字段
public void writeLob() throws Exception{
Connection con=ConnectionFactory.getConnection();
String sql="insert into note values(?,?)";
PreparedStatement ps=con.prepareStatement(sql);
ps.setInt(1, 3);
InputStream in=LobDemoText.class.getClassLoader().getResourceAsStream("JdbcDemo.abc");
ps.setAsciiStream(2, in);
ps.executeUpdate();
con.close();
}
二、图片
我这里为了方便演示就直接用指定后缀名的图片了,实际操作时应该要获取文件名的
同样要先建表
create table img(
id int,
img blob
);
这个img字段的数据类型也有很多种的,这里简单提一下就好,下面列出他的几种:
TinyBlob 最大支持255
Blob 最大支持65k
MediumBlob 最大支持16M
LongBlob 最大支持4G
记得要选择正确大小的数据类型,小了的话数据丢失
然后下图同样方法点进去
再如下操作
下面是java代码
读:
@Test //读取大文件字段
public void readLob() throws Exception{
Connection con=ConnectionFactory.getConnection();
String sql="select * from img where id=1";
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(sql);
if (rs.next()){
InputStream in=rs.getBinaryStream(2);
FileOutputStream out=new FileOutputStream("d:/a/a2.png");
byte buf[]=new byte[1024];
int len=0;
while ((len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
in.close();
out.close();
}
con.close();
}
写:
(这里的写我就是直接指定了哪个文件了,实际上应该要可以选择文件的,这里省略了)
@Test //写大文件字段
public void writeLob() throws Exception{
Connection con=ConnectionFactory.getConnection();
String sql="insert into img values(?,?)";
PreparedStatement ps=con.prepareStatement(sql);
ps.setInt(1, 3);
InputStream in=LobDemoImg.class.getClassLoader().getResourceAsStream("2.png");
ps.setBinaryStream(2, in);
ps.executeUpdate();
con.close();
}