日期:2014-05-19  浏览次数:20649 次

oracle存储图片,用BLOB出现的问题。求教。
代码如下:

Java code

        String URL = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
        Statement stmt;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection(URL, "userName",
                    "passwd");
            stmt = conn.createStatement();
            String sql = "select d_image from display_table where autoid=1 for update";
            ResultSet rs =stmt.executeQuery(sql);
            if (rs.next()) {                    
                oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1);                   
                File file = new File("D:\\test.png");                
                //getBinaryOutputStream(); 这个方法已经过期,不知道用哪个替代
                OutputStream outStream = blob.getBinaryOutputStream();
                InputStream fin = new FileInputStream(file);
                byte[] b = new byte[blob.getBufferSize()];
                        int leng = 0;
                        while ( (leng = fin.read(b)) != -1) {
                          outStream.write(b, 0, leng);
                        }
            }

        }catch (ClassNotFoundException cnf) {
            System.out.println("driver not find:" + cnf);
        } catch (SQLException sqle) {
            System.out.println("can't connection db:" + sqle);
        } catch (Exception e) {
            System.out.println("Failed to load JDBC/ODBC driver.");
        };



无法插入图片
 blob.getBinaryOutputStream(); 这个方法提示过期

------解决方案--------------------
Java code

Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        OutputStream os = null;
        try {
            stmt = conn.createStatement();
            conn.setAutoCommit(false);
            stmt.executeUpdate("insert into t_image (id, image) values (2, empty_blob())");
            rs = stmt.executeQuery("select image from t_image where id=2 for update");
            if (rs.next()) {
                oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("image");
                os = blob.getBinaryOutputStream();
                InputStream is = new FileInputStream("D:/a.jpg");
                byte[] b = new byte[blob.getBufferSize()];
                int i = 0;
                while ((i = is.read(b)) != -1) {
                    os.write(b,0,i);
                }
            }
            os.flush();
            os.close();
            conn.commit();
            conn.setAutoCommit(true);// 恢复现场