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

Cách chèn ảnh vào database Oracle bằng chương trình Java?


Để lưu ảnh trong Oracle, thường dùng kiểu blob. Đảm bảo bảng có kiểu blob:

Name Null? Type 
----------------------------------------- -------- ---------------------------- 
NAME VARCHAR2(255) 
IMAGE BLOB

Các bước chèn ảnh vào Oracle database:

Bước 1: Kết nối database

Dùng getConnection() của DriverManager. Kết nối Oracle bằng URL jdbc:oracle:thin:@localhost:1521/xe (express edition), username, password:

String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe"; 
Connection con = DriverManager.getConnection(oracleUrl, "user_name", "password");

Bước 2: Tạo PreparedStatement

Tạo PreparedStatement bằng prepareStatement() của Connection. Truyền câu insert có placeholder:

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

Bước 3: Thiết lập giá trị cho placeholder

Dùng setter methods của PreparedStatement. Với Blob dùng setBinaryStream() hoặc setBlob(). Truyền chỉ số tham số và InputStream:

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

Bước 4: Thực thi statement

Thực thi PreparedStatement bằng execute() của PreparedStatement.

Ví dụ

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

public class InsertImageToOracleDB { 
    public static void main(String args[]) throws Exception{ 
        // Đăng ký Driver 
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); 
        // Lấy kết nối 
        String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe"; 
        Connection con = DriverManager.getConnection(oracleUrl, "system", "password"); 
        System.out.println("Đã kết nối Oracle database....."); 
        PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?,?)"); 
        pstmt.setString(1, "sample image"); 
        // Chèn Blob 
        InputStream in = new FileInputStream("E:\\images\\cat.jpg"); 
        pstmt.setBlob(2, in); 
        // Thực thi 
        pstmt.execute(); 
        System.out.println("Bản ghi đã chèn"); 
    } 
}

Kết quả

Đã kết nối Oracle database..... 
Bản ghi đã chèn.....