`
starbhhc
  • 浏览: 633031 次
  • 性别: Icon_minigender_2
  • 来自: 深圳
社区版块
存档分类
最新评论

java mysql 读取blob 数据

    博客分类:
  • java
 
阅读更多

ava Mysql存取Blob数据

 

  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);  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics