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

ตัวอย่าง JDBC ดึงค่า Clob ด้วย getCharacterStream()


ResultSet มีเมธอด getClob() ดึง clob datatype นอกจากนี้ยังมี getCharacterStream()

เหมือน getClob() รับ index หรือชื่อคอลัมน์ แต่คืนค่าเป็น object ของ Reader class แทน Clob object

ตัวอย่าง

ตาราง MyData:

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

มีข้อมูลขนาดใหญ่ชื่อ JavaFX โปรแกรมดึงด้วย getCharacterStream():

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 RetrievingClob_CharStream {
    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 MyData");
        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 r = clob.getCharacterStream();
            String filePath = "E:\\Data\\clob_output" + j + ".txt";
            FileWriter writer = new FileWriter(filePath);
            int i;
            while ((i = r.read()) != -1) {
                writer.write(i);
            }
            writer.close();
            System.out.println(filePath);
            j++;
        }
    }
}

ผลลัพธ์

Connection established......
Contents of the table......
JavaFX
E:\Data\clob_output0.txt

เปิดไฟล์ที่ได้จะเห็นเนื้อหา Clob ที่ดึงมา:

ตัวอย่าง JDBC ดึงค่า Clob ด้วย getCharacterStream()