易百教程

358、如何检索 Oracle 数据库中的文件?

PreparedStatement 的 getClob()方法用于从数据库中获取文件信息。让我们看一下检索文件的示例的表结构。

CREATE TABLE  "FILETABLE"   
   (    "ID" NUMBER,   
    "NAME" CLOB  
   )

下面给出了从 Oracle 数据库中检索文件的示例。


import java.io.*;
import java.sql.*;

public class RetrieveFile {

    public static void main(String[] args) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection(
                    "jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");

            PreparedStatement ps = con.prepareStatement("select * from filetable");
            ResultSet rs = ps.executeQuery();
            rs.next();//now on 1st row  

            Clob c = rs.getClob(2);
            Reader r = c.getCharacterStream();

            FileWriter fw = new FileWriter("d:\\retrivefile.txt");

            int i;
            while ((i = r.read()) != -1) {
                fw.write((char) i);
            }

            fw.close();
            con.close();

            System.out.println("success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}