数据库读取和写入大文件


针对大文本:Clob:字符大对象:Character large object
// file.txt的文件保存到数据库中
@Test
public void test(){
Connction conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try{
conn = JdbcUtil.getConnection();
stmt = conn.prepareStatement("insert into count(id,content) values (?,?)");
stmt.setInt(1,1);
// 使用字符流的形式存储,提高效率
File file = new File("c:/file.txt");
Reader reader = new FileReader(file);
stmt.setCharacterStream(2,reader, (int)file.length());
stmt.executeUpdate();
}catch(Exception e){
throw new RuntimeException(e);
}finally{

JdbcUtil.release(rs, stmt, conn);
}
}
// 将id=1的记录content的内容写到磁盘上
@Test
public void test(){
Connction conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try{
conn = JdbcUtil.getConnection();
stmt = conn.prepareStatement("select * from count where id=1");
// 查询结果集
rs = stmt.executeQuery();
if(rs.next()){
// 得到结果字符流
Reader reader = rs.getCharacterStream("content");
// 得到一只笔,写入到文件中
Writer writer = new Writer("c:/deng.txt");
// 开始写入
char[] buf = new char[1024];
int len = -1;
while((len=reader.read(buf))!=-1){
writer.write(buf,0,len);
}
writer.close();
reader.close();
}
}catch(Exception e){
throw new RuntimeException(e);
}finally{

JdbcUtil.release(rs, stmt, conn);
}
}

// 大二进制数据:语音、视频、图片、压缩包.Blob:二进制大对象 Binary Large Object
// 将1.jpg保存到数据库中
@Test
public void test(){
Connction conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try{
conn = JdbcUtil.getConnection();
stmt = conn.prepareStatement("insert into t2(id, content) values (?,?)");
stmt.setInt(1,1);
// 使用字节流传输数据,提高工作效率
InputStream in = new FileInputStream("c:/1.jpg");
stmt.setBinaryStream(2,in, in.available());
stmt.executeUpdate();

}catch(Exception e){
throw new RuntimeException(e);
}finally{

JdbcUtil.release(rs, stmt, conn);
}
}
// 把content的内容写到磁盘上

@Test
public void test(){
Connction conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try{
conn = JdbcUtil.getConnection();
stmt = conn.prepareStatement("select * from count where id=1");
// 查询结果集
rs = stmt.executeQuery();
if(rs.next()){
// 得到结果输入字节流
InputStream in = rs.getBinaryStream("content");
// 字节输出流,将内容输出到对应的文件
OutputStream out = new FileOutputStream("c:/deng.txt");
// 开始写入
byte[] buf = new byte[1024];
int len = -1;
while((len=in.read(buf))!=-1){
out.write(buf,0,len);
}
out.close();
in.close();
}
}catch(Exception e){
throw new RuntimeException(e);
}finally{

JdbcUtil.release(rs, stmt, conn);
}
}

posted @   今夜无风  阅读(372)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示