Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

ดึงไฟล์จากฐานข้อมูลด้วย JDBC


ResultSet มีเมธอด getClob() และ getCharacterStream() ดึง Clob datatype ที่มักเก็บเนื้อหาไฟล์

ทั้งคู่รับ index หรือชื่อคอลัมน์ getClob() คืน Clob object getCharacterStream() คืน Reader object ที่มีเนื้อหา

ตัวอย่าง

ตาราง Articles:

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

มีข้อมูล 3 บทความ (article1, article2, article3)

ดึงไฟล์จากฐานข้อมูลด้วย JDBC

โปรแกรมดึงข้อมูลและบันทึกเป็นไฟล์

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 {
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
        Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
        System.out.println("Connection established......");
        Statement stmt = con.createStatement();
        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