如何使用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+ 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.