java操作blob

原文地址:http://eric-gcm.iteye.com/blog/937860
package com.allan;
import java.sql.*;
import java.io.*;
public class Storeblobfile {


  public static void main(String[] args) {
    try{
      FileInputStream file = new FileInputStream("C:\\shanshui.jpg");
      Class.forName("com.mysql.jdbc.Driver");
      Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=root");
      PreparedStatement ps = conn.prepareStatement("insert into user values(?,?,?)");
      ps.setString(1,"blob");
      ps.setInt(2,23);
      ps.setBinaryStream(3, file, file.available());
      ps.executeUpdate();
      Statement stmt = conn.createStatement();
      ResultSet rs = stmt.executeQuery("select file from user where name = 'blob'");
      while(rs.next()){
      Blob blob = rs.getBlob(1);
      InputStream in = blob.getBinaryStream();
      FileOutputStream fout = new FileOutputStream("C:\\copy.jpg");
      int b = -1;
      while((b=in.read())!=-1){
            fout.write(b);
       }
     }
    }catch(Exception e){
        System.out.println(e.getMessage());
    }
 }

}

//如果有一blob類型的列“content”,要將content中的數據取出來放到String中:

Blob blob = rs.getBlob("content");
int bolblen = (int) blob.length();
byte[] data = blob.getBytes(1, bolblen);
String content = new String(data);

發佈了33 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章