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

วิธี insert รูปภาพเข้า MySQL database ด้วย Java


MySQL ใช้ชนิด BLOB เก็บรูปภาพ ตรวจสอบให้แน่ใจว่าตารางมีคอลัมน์ BLOB:

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

ขั้นตอน insert รูปภาพ:

ขั้นตอน 1: เชื่อมต่อฐานข้อมูล

String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");

ขั้นตอน 2: สร้าง PreparedStatement

PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?, ?)");

ขั้นตอน 3: ตั้งค่า placeholder

ใช้ setter ตามชนิดข้อมูล สำหรับ BLOB ใช้ setBinaryStream() หรือ setBlob() ส่ง InputStream:

pstmt.setString(1, "sample image");
InputStream in = new FileInputStream("E:\\images\\cat.jpg");
pstmt.setBlob(2, in);

ขั้นตอน 4: รันคำสั่ง

pstmt.execute();

ตัวอย่างโปรแกรม

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class InsertImageToMySqlDB {
    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......");
        PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?,?)");
        pstmt.setString(1, "sample image");
        InputStream in = new FileInputStream("E:\\images\\cat.jpg");
        pstmt.setBlob(2, in);
        pstmt.execute();
        System.out.println("Record inserted......");
    }
}

ผลลัพธ์

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