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,如下所示:

以下程序使用 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 从数据库中检索文件?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号