日期:2014-05-16 浏览次数:20643 次
package jdbc; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; /** * * @author HaoWang */ public class BlobTest { public static void main(String[] args) { // create(1,"C:\\a.jpg"); read(1,"C:\\a_bak.jpg"); } public static void create(int bid, String path) { Connection conn = null; String sql = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); sql = "insert into blob_test(bid,content) value(?,?)"; ps = conn.prepareStatement(sql); ps.setInt(1, bid); File file = new File(path); InputStream in = new BufferedInputStream(new FileInputStream(file)); ps.setBinaryStream(2, in, file.length()); int i = ps.executeUpdate(); System.out.println("i="+i); in.close(); } catch (Exception ex) { System.out.println(ex.toString()); } finally { JdbcUtils.free(conn, ps, rs); } } public static void read(int bid, String path) { Connection conn = null; String sql = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); sql = "select content from blob_test where bid=?"; ps = conn.prepareStatement(sql); ps.setInt(1, bid); rs = ps.executeQuery(); while(rs.next()) { InputStream in = rs.getBinaryStream(bid); File file = new File(path); OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); byte[] buff = new byte[1024]; for(int i=0; (i=in.read(buff))>0;) { out.write(buff, 0, i); } out.close(); in.close(); } } catch (Exception ex) { System.out.println(ex.toString()); } finally { JdbcUtils.free(conn, ps, rs); } } }
?