码迷,mamicode.com
首页 > 数据库 > 详细

二进制读取 jdbc

时间:2015-12-24 15:02:18      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

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);
        }
    }
}

 

二进制读取 jdbc

标签:

原文地址:http://www.cnblogs.com/baijin05/p/5072927.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!