zoukankan      html  css  js  c++  java
  • 【转】Oracle中插入和取出图片(用BLOB类型)

    原文地址:http://czllfy.iteye.com/blog/66737

    其他参考资料地址:http://lavasoft.blog.51cto.com/62575/321882/

    要在oracle里面存入图片 用 blob类型 

    首先在数据库里建立: 
    --连接到管理员 
    conn sys/tbsoft as sysdba; 

    --为scott用户授权 
    grant create any directory to scott; 

    --回到scott用户 
    conn scott/tiger; 

    --创建存储图片的表 
    CREATE TABLE IMAGE_LOB (T_ID VARCHAR2 (5) NOT NULL,T_IMAGE BLOB NOT NULL); 

    --创建存储图片的目录 
    CREATE OR REPLACE DIRECTORY IMAGES AS 'C:picture'; 

    --在c:下自己建一个叫picture的文件夹 

    CREATE OR REPLACE PROCEDURE IMG_INSERT (TID VARCHAR2,FILENAME VARCHAR2) AS 
    F_LOB BFILE;--文件类型 
    B_LOB BLOB; 
    BEGIN 
    iNSERT INTO IMAGE_LOB (T_ID, T_IMAGE) 
    VALUES (TID,EMPTY_BLOB ()) RETURN T_IMAGE INTO B_LOB; 
    --插入空的blob 
    F_LOB:= BFILENAME ('IMAGES', FILENAME); 
    --获取指定目录下的文件 
    DBMS_LOB.FILEOPEN(F_LOB, DBMS_LOB.FILE_READONLY); 
    --以只读的方式打开文件 
    DBMS_LOB.LOADFROMFILE (B_LOB, F_LOB,DBMS_LOB.GETLENGTH (F_LOB)); 
    --传递对象 
    DBMS_LOB.FILECLOSE (F_LOB); 
    --关闭原始文件 
    COMMIT; 
    END; 



    --在C:picture下放一张图片1.gif 

    --将该图片存入表 
    call IMG_INSERT('1','1.gif'); 


    然后创建一个web项目 连接数据库后 创建一个BlobDAO类 用来取出表中的blob类型图片 

    public class BlobDAO { 

        private static final BlobDAO instance = new BlobDAO(); 

        private Connection conn = null; 

        private BlobDAO() { 

        } 

        public static BlobDAO getInstance() { 
            return instance; 
        } 

        private void initConn() { 
            conn = DBAccess.getInstance().getConn(); 
        } 

        
        public byte[] getImage(String imgname) { 
            BufferedInputStream ins;//取得BLOB的IO流 
            byte[] bt = null; 

            initConn(); 
            Blob bo = null; 
            PreparedStatement ps = null; 
            ResultSet rs = null; 
            String sql = "select T_IMAGE from IMAGE_LOB where t_id=?"; 
            try { 
                  ps = conn.prepareStatement(sql); 
                  ps.setString(1, imgname); 
                  rs = ps.executeQuery(); 
                  if (rs.next()) { 
                      bo = rs.getBlob("T_IMAGE"); 

                      try { 
                          ins = new BufferedInputStream(bo.getBinaryStream()); 
                          int bufferSize = (int) bo.length();//取得BLOB的长度 
                          bt = new byte[bufferSize]; 
                          try { 
                                ins.read(bt, 0, bufferSize); 
                          } catch (IOException e) { 
                                // TODO Auto-generated catch block 
                                e.printStackTrace(); 
                          } 
                          //建立字节缓存 
                      } catch (SQLException e) { 
                          // TODO Auto-generated catch block 
                          e.printStackTrace(); 
                      } 

                  } 
            } catch (SQLException e) { 
                  // TODO Auto-generated catch block 
                  e.printStackTrace(); 
            } finally { 
                  try { 
                      rs.close(); 
                      ps.close(); 
                      conn.close(); 
                  } catch (SQLException e) { 
                      // TODO Auto-generated catch block 
                      e.printStackTrace(); 
                  } 
            } 

            return bt; 
        } 



    在action里面调用getImage()方法并显示图片在页面上 

    public ActionForward execute(ActionMapping mapping, ActionForm form, 
                  HttpServletRequest request, HttpServletResponse response) { 
            // TODO Auto-generated method stub 
            
            BlobDAO blobDAO = BlobDAO.getInstance(); 
            
            byte[] bs = blobDAO.getImage("1"); 
            
            try { 
                  
                  response.getOutputStream().write(bs); 
                  
            } catch (IOException e) { 
                  // TODO Auto-generated catch block 
                  e.printStackTrace(); 
            } 
            
            return null; 
        } 

    添加图片到数据库 

    请在c盘下放入图片--c:\4.gif 

    public void savaImg(String imgId) { 
               //传的是存入数据库图片的id 
               initConn(); 
               Statement st = null; 
               BLOB blob = null; //图片类型 
               OutputStream outputStream = null; //输出流 
               File file = null; //文件 
               InputStream inputStream = null; //输入流 
               ResultSet rs = null; 
               try { 
                     conn.setAutoCommit(false); //事物由程序员操作 
                     st = conn.createStatement(); 
                     st.executeQuery("insert into IMAGE_LOB values('"+ imgId +"',empty_blob())"); 
                     rs = st.executeQuery("select T_IMAGE from IMAGE_LOB where t_id='"+ imgId +"' for update"); 
                     if (rs.next()) { 
                           blob = (BLOB) rs.getBlob(1); 
                           outputStream = blob.getBinaryOutputStream(); 
                           file = new File("c:\4.gif"); 
                           inputStream = new FileInputStream(file); 
                           byte[] b = new byte[blob.getBufferSize()]; 
                           int len = 0; 
                           while ((len = inputStream.read(b)) != -1) { 
                                 System.out.println(len); 
                                 outputStream.write(b, 0, len); 
                           } 
                     } 

               } catch (SQLException e) { 
                     // TODO Auto-generated catch block 
                     e.printStackTrace(); 
               } catch (FileNotFoundException e) { 
                     // TODO Auto-generated catch block 
                     e.printStackTrace(); 
               } catch (IOException e) { 
                     // TODO Auto-generated catch block 
                     e.printStackTrace(); 
               } finally { 
                     try { 
                           inputStream.close(); 
                           outputStream.flush(); 
                           outputStream.close(); 
                           rs.close(); 
                           st.close(); 
                           conn.commit(); 
                           conn.close(); 
                     } catch (IOException e) { 
                           // TODO Auto-generated catch block 
                           e.printStackTrace(); 
                     } catch (SQLException e) { 
                           // TODO Auto-generated catch block 
                           e.printStackTrace(); 
                     } 

               } 
         } 

    Java在postgresql中插入和读取图片

    原文:http://blog.csdn.net/movture/article/details/8782402

    注意:

    ① 此例中postgresql 用byeta类型的字段保存图片。

    ② JAVA代码第71行,setBinaryStream 方法第三个参数需要是整数型。若没有参数或参数被设置为长整型,虽然编译会通过,但执行会出错。

    JAVA代码

    [java] view plaincopy
     
    1. import java.io.File;  
    2. import java.io.FileInputStream;  
    3. import java.io.FileNotFoundException;  
    4. import java.io.FileOutputStream;  
    5. import java.io.IOException;  
    6. import java.io.InputStream;  
    7. import java.sql.Connection;  
    8. import java.sql.DriverManager;  
    9. import java.sql.PreparedStatement;  
    10. import java.sql.ResultSet;  
    11. import java.sql.SQLException;  
    12.   
    13. public class PostgresTest {  
    14.   
    15.     private Connection conn = null;  
    16.     private PreparedStatement ps = null;  
    17.   
    18.     private final String driver = "org.postgresql.Driver";  
    19.     private final String ip = "127.0.0.1";  
    20.     private final String port = "5432";  
    21.     private final String database_name = "test";  
    22.     private final String user = "postgres";  
    23.     private final String password = "123456";  
    24.   
    25.     public PostgresTest() {  
    26.   
    27.         try {  
    28.             this.getConnection();  
    29.             System.out.println("数据库 " + ip + "/" + database_name + " 连接成功");  
    30.         } catch (ClassNotFoundException e) {  
    31.             System.err.println("没有找到驱动程序:" + driver);  
    32.         } catch (SQLException e) {  
    33.             System.err.println("数据库 " + ip + "/" + database_name + " 连接失败");  
    34.         }  
    35.     }  
    36.   
    37.     /** 
    38.      * 获得数据库连接 
    39.      *  
    40.      * @return 数据库连接 
    41.      * @throws ClassNotFoundException 
    42.      * @throws SQLException 
    43.      */  
    44.     private Connection getConnection() throws ClassNotFoundException,  
    45.             SQLException {  
    46.         Class.forName(driver);  
    47.         conn = DriverManager.getConnection("jdbc:postgresql://" + ip + ":"  
    48.                 + port + "/" + database_name, user, password);  
    49.         return conn;  
    50.     }  
    51.   
    52.     /** 
    53.      * 向数据库上传图片 
    54.      *  
    55.      * @param path 
    56.      * @param name 
    57.      */  
    58.     public void uploadImage(String path, String name) {  
    59.   
    60.         String sql = "insert into notice_image(image_name,image_file) values(?,?)";  
    61.   
    62.         try {  
    63.             ps = conn.prepareStatement(sql);  
    64.   
    65.             // 设置图片名称  
    66.             ps.setString(1, name);  
    67.   
    68.             // 设置图片文件  
    69.             File file = new File(path + "\" + name);  
    70.             FileInputStream inputStream = new FileInputStream(file);  
    71.             ps.setBinaryStream(2, inputStream, (int) file.length());  
    72.   
    73.             // 执行SQL  
    74.             ps.execute();  
    75.             ps.close();  
    76.   
    77.             System.out.println(path + "\" + name+" 已上传");  
    78.   
    79.         } catch (SQLException e) {  
    80.             System.err.println("SQL " + sql + " 错误");  
    81.         } catch (FileNotFoundException e) {  
    82.             System.err.println("图片 " + path + "\" + name + " 没有找到");  
    83.         }  
    84.     }  
    85.   
    86.     /** 
    87.      * 从数据库下载图片 
    88.      *  
    89.      * @param path 
    90.      */  
    91.     public void downloadImage(String path) {  
    92.   
    93.         String sql = "SELECT image_name,image_file FROM notice_image";  
    94.         String name = "";  
    95.         try {  
    96.             ps = conn.prepareStatement(sql);  
    97.             ResultSet rs = ps.executeQuery();  
    98.   
    99.             while (rs.next()) {  
    100.   
    101.                 name = rs.getString(1);  
    102.                 InputStream inputStream = rs.getBinaryStream(2);  
    103.                 FileOutputStream outputStream = new FileOutputStream(new File(  
    104.                         path + "\_" + name));  
    105.   
    106.                 int i = inputStream.read();  
    107.                 while (i != -1) {  
    108.                     outputStream.write(i);  
    109.                     i = inputStream.read();  
    110.                 }  
    111.                 outputStream.close();  
    112.   
    113.                 System.out.println(path + "\_" + name + " 已下载");  
    114.             }  
    115.   
    116.             rs.close();  
    117.             ps.close();  
    118.   
    119.         } catch (SQLException e) {  
    120.             System.err.println("SQL " + sql + " 错误");  
    121.         } catch (FileNotFoundException e) {  
    122.             System.err.println(path + "\_" + name + " 创建失败");  
    123.         } catch (IOException e) {  
    124.             e.printStackTrace();  
    125.         }  
    126.     }  
    127.   
    128.     /** 
    129.      * @param args 
    130.      */  
    131.     public static void main(String[] args) {  
    132.   
    133.         PostgresTest o = new PostgresTest();  
    134.         o.uploadImage("d:""23.jpg");  
    135.         o.uploadImage("d:""24.jpg");  
    136.         o.downloadImage("d:");  
    137.   
    138.     }  
    139.   
    140. }  

    Postgres建表SQL

    [sql] view plaincopy
     
    1. -- Table: notice_image  
    2.   
    3. -- DROP TABLE notice_image;  
    4.   
    5. CREATE TABLE notice_image  
    6. (  
    7.   id serial NOT NULL,  
    8.   image_name character varying(256) NOT NULL DEFAULT ''::character varying,  
    9.   image_file bytea,  
    10.   CONSTRAINT pk_notice_image PRIMARY KEY (id)  
    11. )  
    12. WITH (OIDS=FALSE);  
    13. ALTER TABLE notice_image OWNER TO postgres;  
  • 相关阅读:
    王道训练营-C语言-1
    错排问题
    王道训练营-C语言-1
    图文处理 生成海报
    根据经纬度按距离排序
    vue总结
    docker+consul
    doker es
    知识库
    php笔记
  • 原文地址:https://www.cnblogs.com/liuyuanyuanGOGO/p/oracle_blob.html
Copyright © 2011-2022 走看看