java - mysql 读取blob 数据

本文介绍了如何使用Java将图片文件存储到数据库中,并通过SQL查询获取数据后保存到本地文件。重点在于使用Java操作文件输入输出、数据库连接与查询,以及将获取的数据转换为本地文件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. package com.allan;  
  2. import java.sql.*;  
  3. import java.io.*;  
  4. public class Storeblobfile {  
  5.   
  6.   
  7.   public static void main(String[] args) {  
  8.     try{  
  9.       FileInputStream file = new FileInputStream("C:\\shanshui.jpg");  
  10.       Class.forName("com.mysql.jdbc.Driver");  
  11.       Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=root");  
  12.       PreparedStatement ps = conn.prepareStatement("insert into user values(?,?,?)");  
  13.       ps.setString(1,"blob");  
  14.       ps.setInt(2,23);  
  15.       ps.setBinaryStream(3, file, file.available());  
  16.       ps.executeUpdate();  
  17.       Statement stmt = conn.createStatement();  
  18.       ResultSet rs = stmt.executeQuery("select file from user where name = 'blob'");  
  19.       while(rs.next()){  
  20.       Blob blob = rs.getBlob(1);  
  21.       InputStream in = blob.getBinaryStream();  
  22.       FileOutputStream fout = new FileOutputStream("C:\\copy.jpg");  
  23.       int b = -1;  
  24.       while((b=in.read())!=-1){  
  25.             fout.write(b);  
  26.        }  
  27.      }  
  28.     }catch(Exception e){  
  29.         System.out.println(e.getMessage());  
  30.     }  
  31.  }  
  32.   
  33. }  
  34.   
  35. //如果有一blob类型的列“content”,要将content中的数据取出来放到String中:  
  36.   
  37. Blob blob = rs.getBlob("content");  
  38. int bolblen = (int) blob.length();  
  39. byte[] data = blob.getBytes(1, bolblen);  
  40. String content = new String(data);  

 

若转化过程出现乱码:  http://blog.163.com/woshihezhonghua@126/blog/static/127143636201311302459696/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值