标签:
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); } } }
标签:
原文地址:http://www.cnblogs.com/yjtm53/p/4204722.html