码迷,mamicode.com
首页 > 其他好文 > 详细

处理Blob

时间:2015-01-05 23:21:39      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

1 二进制文本的一种数据

package lianxi1;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import org.junit.Test;

public class TestBlob {
//读取blob数据
@Test
 public void readBlob(){
    System.out.println("ok");
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
      try {
        conn = JdbcTools.getConnection();
        String sql = "SELECT * FROM student WHERE flowId = ?";
        ps = conn.prepareStatement(sql);
        ps.setInt(1, 12);
        rs = ps.executeQuery();
        System.out.println(rs.next());
        if(rs.next()){
            Blob picture = rs.getBlob(7);
            InputStream is = picture.getBinaryStream();
            OutputStream os = new FileOutputStream("2.jpg");
            byte[] b = new byte[1024];
            int len;
            while((len=is.read(b))!=-1){
                os.write(b, 0, len);
            }
            os.close();
            is.close();
        }
        
        
    } catch (Exception e) {
        e.printStackTrace();
    }
     finally{
        
        JdbcTools.release(rs, ps, conn);
    }
}
// 插入blob数据    
@Test
  public void insertBlob(){
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try{
        conn = JdbcTools.getConnection();
        String sql = "INSERT INTO student(flowId,type,id_Card,exam_Card,studentName,grade,picture) VALUES(?,?,?,?,?,?,?)";
        ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS );
        ps.setInt(1,13);
        ps.setInt(2,5);
        ps.setString(3,"23424141");
        ps.setString(4,"3432141");
        ps.setString(5,"afddfdc");
        ps.setInt(6,99);
        // 插入blob数据
        InputStream is = new FileInputStream("1.jpg");
        ps.setBlob(7, is);
        ps.executeUpdate();
        // 读取主键的值
        rs = ps.getGeneratedKeys();
        if(rs.next()){
            System.out.println(rs.getInt(1));
        }
        
    }catch(Exception ex){ex.printStackTrace();}
    finally{
        
        JdbcTools.release(rs, ps, conn);
    }
}
}

处理Blob

标签:

原文地址:http://www.cnblogs.com/yjtm53/p/4204722.html

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