import java.sql.*; import java.io.*; public class Storeblobfile { public static void main(String[] args) { try{ //Save To DB 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(); //Get Blob 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(); //Write to File 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()); } } }
|