zhou_hong_liang 发表于 2013-1-15 02:58:08

java 操作oracle表中的图片

package com;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;public class DBBLOG {static Connection connection;static String url = "jdbc:oracle:thin:@10.12.100.22:1521:liang";static String username = "scott";static String password = "tiger";static PreparedStatement ps;static ResultSet rs;/** * @param args */public static void main(String[] args) {getConnection();try {writeImg("f:\\a.jpg","4");readImg("f:\\b.jpg","4");connection.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public static Connection getConnection() {try {Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();connection = DriverManager.getConnection(url, username, password);} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}return connection;}// 图片添加到数据库public static void writeImg(String url,String id) throws FileNotFoundException,SQLException {File in_f = new File(url);FileInputStream f_in = new FileInputStream(in_f);String sql = "INSERT INTO T_IMG VALUES (?,?)";ps = connection.prepareStatement(sql);ps.setString(1, id);ps.setBinaryStream(2, f_in, (int) in_f.length());ps.executeUpdate();connection.commit();ps.close();}public static void readImg(String url,String id) throws SQLException, IOException {File out_f = new File(url);OutputStream os = new FileOutputStream(out_f);String sql = "SELECT * FROM T_IMG WHERE ID = "+id;InputStream in = null;ps = connection.prepareStatement(sql);rs = ps.executeQuery();while (rs.next()) {in = rs.getBinaryStream("IMG");byte[] b = new byte;int len = -1;while ((len = in.read(b)) != -1) {os.write(b, 0, len);}}os.flush();os.close();if (in != null)in.close();}}
页: [1]
查看完整版本: java 操作oracle表中的图片