ResultSet接口提供名為getClob()和getCharacterStream()的方法來(lái)檢索Clob數(shù)據(jù)類(lèi)型,通常存儲(chǔ)文件的內(nèi)容。
這些方法接受表示列索引的整數(shù)(或表示列名稱(chēng)的字符串值)并檢索指定列處的值.
區(qū)別在于 getClob() 方法返回一個(gè) Clob 對(duì)象,而 getCgaracterStream() 方法返回一個(gè)包含 Clob 數(shù)據(jù)類(lèi)型內(nèi)容的 Reader 對(duì)象。
示例
假設(shè)我們?cè)跀?shù)據(jù)庫(kù)中創(chuàng)建了一個(gè)名為 Articles 的表,并具有以下描述。
+---------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | Article | longtext | YES | | NULL | | +---------+--------------+------+-----+---------+-------+
登錄后復(fù)制
并且,我們?cè)谄渲胁迦肓巳恼?,名稱(chēng)為文章 1、文章 2 和文章 3,如下所示:
示例
以下程序使用 getString() 和 getClob() 方法檢索表 Articles 的內(nèi)容,并將其保存在指定文件。
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++;
}
}
}
登錄后復(fù)制
輸出
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
登錄后復(fù)制
以上就是我們?nèi)绾问褂?JDBC 從數(shù)據(jù)庫(kù)中檢索文件?的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.92cms.cn其它相關(guān)文章!






