一般來說,文件的內(nèi)容在 MySQL 數(shù)據(jù)庫中存儲在 Clob(TINYTEXT、TEXT、MEDIUMTEXT、LONGTEXT)數(shù)據(jù)類型下。
JDBC 提供了對 Clob 數(shù)據(jù)類型的支持,將文件的內(nèi)容存儲到數(shù)據(jù)庫的表中。
PreparedStatement接口的 setCharacterStream() 方法接受一個整數(shù),表示參數(shù)的索引和 Reader 對象作為參數(shù)。
并將給定讀取器對象(文件)的內(nèi)容設(shè)置為指定索引中的參數(shù)(占位符)的值。
每當您需要發(fā)送非常大的文本值時,您都可以使用此方法。
使用 JDBC 存儲文本文件:
如果您需要使用以下方式將文件存儲在數(shù)據(jù)庫中JDBC程序創(chuàng)建具有Clob(TINYTEXT,TEXT,MEDIUMTEXT,LONGTEXT)數(shù)據(jù)類型的表,如下所示:
CREATE TABLE Articles(Name VARCHAR(255), Article LONGTEXT);
登錄后復(fù)制
現(xiàn)在,使用 JDBC 連接到數(shù)據(jù)庫并準備一個 PreparedStatement 將值插入到上面創(chuàng)建的表中:
String query = "INSERT INTO Tutorial(Name, Article) VALUES (?,?)";PreparedStatement pstmt = con.prepareStatement(query);
登錄后復(fù)制
使用PreparedStatement接口的setter方法設(shè)置占位符的值,并使用setCharacterStream()方法設(shè)置Clob數(shù)據(jù)類型的值。
示例
以下是演示如何插入文件的示例
使用 JDBC 程序連接到 MySQL 數(shù)據(jù)庫。在這里,我們創(chuàng)建了一個具有 Clob 數(shù)據(jù)類型的表,并在其中插入了值。
import java.io.FileReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class InsertingFileToDatabase { 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......"); //Inserting values String query = "INSERT INTO Articles(Name, Article) VALUES (?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "article1"); FileReader reader = new FileReader("E:\data\article1.txt"); pstmt.setCharacterStream(2, reader); pstmt.execute(); pstmt.setString(1, "article2"); reader = new FileReader("E:\data\article2.txt"); pstmt.setCharacterStream(2, reader); pstmt.execute(); pstmt.setString(1, "article3"); reader = new FileReader("E:\data\article3.txt"); pstmt.setCharacterStream(2, reader); pstmt.execute(); System.out.println("Data inserted......"); } }
登錄后復(fù)制
輸出
Connection established...... Data inserted......
登錄后復(fù)制
使用 MySQL Workbench,您可以將表的內(nèi)容導(dǎo)出到各種文件,例如 html 文件、.csv 文件、文本文件等。如果在將數(shù)據(jù)插入到 HTML 文件后導(dǎo)出表的內(nèi)容,其輸出將如下所示:
以上就是我們?nèi)绾问褂?JDBC 將文件插入/存儲到 MySQL 數(shù)據(jù)庫中?的詳細內(nèi)容,更多請關(guān)注www.92cms.cn其它相關(guān)文章!