Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Ví dụ JDBC chèn giá trị cho kiểu Clob data type vào bảng?


Giả sử đã có bảng MyData trong database:

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

Để chèn giá trị vào kiểu clob dùng JDBC, cần phương thức đọc nội dung file và thiết lập cho hàng database. PreparedStatement cung cấp các phương thức này.

Phương thức void setCharacterStream(int parameterIndex, Reader reader) thiết lập nội dung reader object làm giá trị cho tham số tại chỉ số cho trước. Các biến thể:

  • void setCharacterStream(int parameterIndex, Reader reader, int length)

  • void setCharacterStream(int parameterIndex, Reader reader, long length)

Phương thức void setClob(int parameterIndex, Clob x) thiết lập java.sql.Clob object làm giá trị cho tham số tại chỉ số cho trước. Các biến thể:

  • void setClob(int parameterIndex, Reader reader)

  • void setClob(int parameterIndex, Reader reader, long length)

Bạn có thể dùng một trong các phương thức này để thiết lập giá trị cho kiểu Clob.

Ví dụ

Ví dụ thiết lập giá trị cho kiểu Clob dùng setClob():

import java.io.FileReader; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 

public class InsertingValueInClob { 
    public static void main(String args[]) throws Exception { 
        // Đăng ký Driver 
        DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 
        // Lấy kết nối 
        String mysqlUrl = "jdbc:mysql://localhost/sampleDB"; 
        Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); 
        System.out.println("Kết nối thành công......"); 
        // Chèn giá trị 
        String query = "INSERT INTO MyData(Name, Article ) VALUES (?, ?)"; 
        PreparedStatement pstmt = con.prepareStatement(query); 
        pstmt.setString(1, "JavaFX"); 
        FileReader reader = new FileReader("E:\\images\\javafx.txt"); 
        pstmt.setClob(2, reader); 
        pstmt.execute(); 
        System.out.println("Dữ liệu đã chèn"); 
    } 
}

Kết quả

Kết nối thành công...... 
Bảng đã tạo...... 
Nội dung bảng: 
JavaFX 
E:\images\MyData_clob_output1.txt

Xem giá trị clob trong bản ghi bằng MySQL Workbench, thấy text data đã chèn:

Ví dụ JDBC chèn giá trị cho kiểu Clob data type vào bảng?