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

ตัวอย่าง JDBC insert ค่า Blob datatype ลงตาราง


สมมติตาราง MyTable มีโครงสร้าง:

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

เมธอดสำหรับ insert Blob:

  • void setBinaryStream(int parameterIndex, InputStream x) ตั้งค่า InputStream จนจบไฟล์

  • รูปแบบอื่น: setBinaryStream(int, InputStream, int length) และ setBinaryStream(int, InputStream, long length)

  • void setBlob(int parameterIndex, Blob x) ตั้งค่า Blob object

  • รูปแบบอื่น: setBlob(int, InputStream) และ setBlob(int, InputStream, long length)

ตัวอย่างใช้ setBinaryStream()

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class IndertingValueForBlob {
    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......");
        String query = "INSERT INTO MyTable(Name,image) VALUES (?, ?)";
        PreparedStatement pstmt = con.prepareStatement(query);
        pstmt.setString(1, "sample_image");
        FileInputStream fin = new FileInputStream("E:\\images\\cat.jpg");
        pstmt.setBinaryStream(2, fin);
        pstmt.execute();
        System.out.println("Record inserted ...");
    }
}

ผลลัพธ์

Connection established......
Record inserted ......

ดูค่า BLOB ใน MySQL Workbench จะเห็นรูปภาพที่ insert

ตัวอย่าง JDBC insert ค่า Blob datatype ลงตาราง