JDBC — 处理BLOB类型数据

Person.java
    
public class Person{
 
    private int id;
    private String name;
    private String city;
    private int age;
    private float salary;
    private byte[] head;
 
    public Person(){
        super();
    }
 
    public Person(int id,String name,String city,int age,float salary,byte[] head){
        super();
        this.id = id;
        this.name = name;
        this.city = city;
        this.age = age;
        this.salary = salary;
        this.head = head;
    }
 
    //...get、set方法
 
}
    
@Test
public void testAddPerson() throws Exception{
 
    FileInputStream fis = new FileInputStream("1.jpg");
    byte[] bs = inputStream2Byte(fis);
    addPerson(new Person(0,"HeHe2","BJ",23,1300,bs));
}
 
/*
 * 插入数据
 */
public static void addPerson(Person p) throws Exception{
    String sql = "insert into person(id,name,city,age,salary,head) values(?,?,?,?,?,?)";
    JdbcTools.update(sql,p.getId(),p.getName(),p.getCity(),p.getAge(),p.getSalary(),p.getHead());
}
 
/*
 * 输入流转换为字节数组
 * @param inStream
 * @return
 * @throws Exception
 */
public static byte[] inputStream2Byte(InputStream inStream) throws Exception{
    ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = -1;
    while((len = inStream.read(buffer)) != -1){
        outSteam.write(buffer,0,len);
    }
    outSteam.close();
    inStream.close();
    return outSteam.toByteArray();
}

JdbcTools.update()方法

    
/*
 * 通用的增删改方法
 * 执行SQL语句,使用PreparedStatemnt
 * @param sql 带占位符的sql语句
 * @param args 填写SQL占位符的可变参数
 */
public static void update(String sql,Object...args){
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
     
    try{
        con = JdbcTools.getConnection();
        ps = con.prepareStatement(sql);
         
        for(int i = 0;i < args.length;i++){
            ps.setObject(i + 1,args[i]);
        }
         
        ps.execute();
         
    }catch (Exception e) {
        e.printStackTrace();
    }
    finally{
        JdbcTools.releaseResource(con,ps,rs);
    }
}
1
    
<font size="3" color="#ff0000">结果:</font>
1
    
<font size="3" color="#ff0000"></font>

image

     在最后BLOb中右键另存为图片即可看到。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值