如何使用JDBC從資料庫中檢索檔案?


ResultSet介面提供了名為getClob()getCharacterStream()的方法來檢索Clob資料型別,其中通常儲存檔案的內容。

這些方法接受一個整數,表示列的索引(或表示列名稱的字串值),並檢索指定列的值。

區別在於getClob()方法返回一個Clob物件,而getCgaracterStream()方法返回一個Reader物件,其中包含Clob資料型別的內容。

示例

假設我們在資料庫中建立了一個名為Articles的表,其描述如下。

+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| Name    | varchar(255) | YES  |     | NULL    |       |
| Article | longtext     | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+

並且,我們已經向其中插入了三篇文章,名稱分別為article 1、article 2和article 3,如下所示

示例

以下程式使用getString()和getClob()方法檢索Articles表的內容,並將其儲存到指定的檔案中。

import java.io.FileWriter;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingFileFromDatabase {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql:///sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating aStatement
      Statement stmt = con.createStatement();
      //Retrieving the data
      ResultSet rs = stmt.executeQuery("select * from Articles");
      int j = 0;
      System.out.println("Contents of the table are: ");
      while(rs.next()) {
         System.out.println(rs.getString("Name"));
         Clob clob = rs.getClob("Article");
         Reader reader = clob.getCharacterStream();
         String filePath = "E:\Data\clob_output"+j+".txt";
         FileWriter writer = new FileWriter(filePath);
         int i;
         while ((i = reader.read())!=-1) {
            writer.write(i);
         }
         writer.close();
         System.out.println(filePath);
         j++;
      }
   }
}

輸出

Connection established......
Contents of the table are:
article1
E:\Data\clob_output0.txt
article2
E:\Data\clob_output1.txt
article3
E:\Data\clob_output2.txt

更新於:2020年6月27日

1K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告