数据库读取和写入大文件



针对大文本: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);
}
}

优质内容筛选与推荐>>
1、java内部类,抽象类,继承,接口,异常的处理等
2、Codeforces Round #490 (Div. 3) A
3、(原)用C#在WinXP和WinCE里获取应用程序当前路径的通用函数
4、mysql内核 innodb存储引警(卷1)配书 用VS 2003 编绎 mysql-3.23.49 源代码
5、c++ 一个类使用另外一个类的变量或方法


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号