如何使用 JDBC 从数据库中检索文件?
mysqlmysqli databasejava 8jdbc更新于 2025/1/26 12:28:17
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 | | +---------+--------------+------+-----+---------+-------+
此外,我们在其中插入了三篇文章,名称分别为文章 1、文章 2 和文章 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://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
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

