操作大文本数据存储在数据库中 mysql中有个lob

/*
create table t2(
id int primary key,
content longtext
);
*/
//插入大文本数据
@Test
public void testTextWrite() throws Exception{
Connection conn = JdbcUtil.getConnection();
PreparedStatement stmt = conn.prepareStatement("insert into t2 (id,content) values (?,?)");
stmt.setInt(1, 1);

File file = new File("src/jpm.txt");
Reader reader = new FileReader(file);
stmt.setCharacterStream(2, reader, (int)file.length());//MySQL驱动对于setCharacterStream(int,Reader,long)根本没有实现

stmt.executeUpdate();

JdbcUtil.release(null, stmt, conn);
}
//取出大文本数据
@Test
public void testTextRead() throws Exception{
Connection conn = JdbcUtil.getConnection();
PreparedStatement stmt = conn.prepareStatement("select * from t2 where id=1");
ResultSet rs = stmt.executeQuery();
if(rs.next()){
Reader r = rs.getCharacterStream("content");
//写到磁盘上
Writer w = new FileWriter("d:/jpm.txt");
char c[] = new char[1024];
int len = -1;
while((len=r.read(c))!=-1){
w.write(c, 0, len);
}
r.close();
w.close();
}

JdbcUtil.release(rs, stmt, conn);
}
/*
create table t3(
id int primary key,
content longblob
);
*/
//插入大二进制数据
@Test
public void testBlobWrite() throws Exception{
Connection conn = JdbcUtil.getConnection();
PreparedStatement stmt = conn.prepareStatement("insert into t3 (id,content) values (?,?)");
stmt.setInt(1, 1);
InputStream in = new FileInputStream("src/19.jpg");
stmt.setBinaryStream(2, in, in.available());

stmt.executeUpdate();

JdbcUtil.release(null, stmt, conn);
}
//取出大二进制数据
@Test
public void testBlobRead() throws Exception{
Connection conn = JdbcUtil.getConnection();
PreparedStatement stmt = conn.prepareStatement("select * from t3 where id=1");
ResultSet rs = stmt.executeQuery();
if(rs.next()){
InputStream in = rs.getBinaryStream("content");
//写到磁盘上
OutputStream out = new FileOutputStream("d:/a.jpg");
byte b[] = new byte[1024];
int len = -1;
while((len=in.read(b))!=-1){
out.write(b, 0, len);
}
in.close();
out.close();
}

JdbcUtil.release(rs, stmt, conn);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值