测试表
create table TEST_IMG ( ID INTEGER not null, NAME VARCHAR2(32), IMAGE BLOB );
1、使用JDBC演示
2、IMAGE字段存储一个图片
程序代码如下:
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Test { public static final String DRIVER = "oracle.jdbc.driver.OracleDriver"; public static final String URL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; public static final String USERNAME = "test"; public static final String PASSWORD = "test"; static { try { Class.forName(DRIVER); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { if (download()) { System.out.println("图片下载成功"); } else { System.out.println("图片下载失败"); } } public static boolean download() { Connection conn = getConnection(); Statement sta = null; ResultSet rs = null; try { sta = conn.createStatement(); // image字段为BLOG字段 String sql = "Select name, image from test_img where id=‘1‘"; rs = sta.executeQuery(sql); while (rs.next()) { // 输出文件名 String name = rs.getString("name"); oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("image"); String filepath = "D:/" + name + ".jpg"; System.out.println("输出文件路径为:" + filepath); InputStream input = blob.getBinaryStream(); FileOutputStream out = new FileOutputStream(filepath); int len = (int) blob.length(); byte buffer[] = new byte[len]; while ((len = input.read(buffer)) != -1) { out.write(buffer, 0, len); } out.close(); input.close(); } } catch (SQLException e) { e.printStackTrace(); return false; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { try { rs.close(); sta.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); return false; } } return true; } /** * 获得Connection */ public static Connection getConnection() { Connection conn = null; try { conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (SQLException e) { e.printStackTrace(); } return conn; } }
作者:itmyhome
原文地址:http://blog.csdn.net/itmyhome1990/article/details/43227305