package com.itheima.clob.test; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.junit.Test; import com.itheima.utils.JdbcUtil; /** * 大二进制数据读写(图片,电影,音乐,字节码文件) Mysq: blob longblob * @author wangli * * use day16; create table testblob( id int primary key, content longblob ); * */ public class BlobTest02 { //写一个图片到数据表中 测试时显示记录,注意 select id from testblob; @Test public void testAddBlob(){ Connection con = null; PreparedStatement st =null; try { con = JdbcUtil.getConnection(); String sql="insert into testblob values(?,?)"; st = con.prepareStatement(sql); //赋值 st.setInt(1, 1); InputStream is = new FileInputStream("src/1.jpg");//找到src下的文件1.jpg st.setBinaryStream(2, is, is.available()); st.executeUpdate(); } catch (Exception e) { e.printStackTrace(); }finally{ JdbcUtil.release(null, st, con); } } @Test //读取一个图片 public void testReaderblob(){ Connection con = null; PreparedStatement st =null; ResultSet rs = null; try { con = JdbcUtil.getConnection(); String sql="select * from testblob where id=?"; st = con.prepareStatement(sql); //赋值 st.setInt(1, 1); //3.读取 rs = st.executeQuery(); if(rs.next()){ //结果集中有数据 InputStream is = rs.getBinaryStream("content"); OutputStream os = new FileOutputStream("d:/1.jpg"); int len=-1; byte buffer[] = new byte[1024]; while((len=is.read(buffer))!=-1){ os.write(buffer, 0, len); } os.close(); is.close(); } } catch (Exception e) { e.printStackTrace(); }finally{ JdbcUtil.release(null, st, con); } } }
时间: 2024-11-06 16:11:32