登录
首页 >  数据库 >  MySQL

我们如何使用 JDBC 从数据库中检索文件?

来源:tutorialspoint

时间:2023-08-29 16:09:47 126浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《我们如何使用 JDBC 从数据库中检索文件?》,以下内容主要包含等知识点,如果你正在学习或准备学习数据库,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

ResultSet接口提供名为getClob()getCharacterStream()的方法来检索Clob数据类型,通常存储文件的内容。

这些方法接受表示列索引的整数(或表示列名称的字符串值)并检索指定列处的值.

区别在于 getClob() 方法返回一个 Clob 对象,而 getCgaracterStream() 方法返回一个包含 Clob 数据类型内容的 Reader 对象。

示例

假设我们在数据库中创建了一个名为 Articles 的表,并具有以下描述。

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

并且,我们在其中插入了三篇文章,名称为文章 1、文章 2 和文章 3,如下所示:

我们如何使用 JDBC 从数据库中检索文件?

示例

以下程序使用 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://localhost/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

终于介绍完啦!小伙伴们,这篇关于《我们如何使用 JDBC 从数据库中检索文件?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布数据库相关知识,快来关注吧!

声明:本文转载于:tutorialspoint 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>