Computer >> 컴퓨터 >  >> 프로그래밍 >> MySQL

JDBC로 BLOB 데이터 삽입하기 – setBinaryStream()과 setBlob() 메서드 활용 예제

데이터베이스에 다음과 같은 구조를 가진 MyTable 테이블이 이미 존재한다고 가정해 보겠습니다.

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

JDBC 프로그램을 사용하여 BLOB 데이터 유형 컬럼에 값을 삽입하려면 바이너리 스트림(binary stream) 데이터를 설정하는 메서드를 사용해야 합니다. PreparedStatement 인터페이스는 이미지와 같은 BLOB 데이터를 테이블에 삽입할 수 있도록 다음과 같은 메서드들을 제공합니다.

1. setBinaryStream() 메서드

void setBinaryStream(int parameterIndex, InputStream x) 메서드는 지정된 입력 스트림의 데이터(파일 끝까지)를 해당 인덱스의 파라미터 값으로 설정합니다.

이 메서드의 다른 변형 형태는 다음과 같습니다.

  • void setBinaryStream(int parameterIndex, InputStream x, int length)
  • void setBinaryStream(int parameterIndex, InputStream x, long length)

2. setBlob() 메서드

void setBlob(int parameterIndex, Blob x) 메서드는 지정된 Blob 객체를 해당 인덱스의 파라미터 값으로 설정합니다.

이 메서드의 다른 변형 형태는 다음과 같습니다.

  • void setBlob(int parameterIndex, InputStream inputStream)
  • void setBlob(int parameterIndex, InputStream inputStream, long length)

즉, 위 두 가지 메서드 중 어느 것을 사용해도 BLOB 데이터 유형에 값을 설정할 수 있습니다.

예제 코드

다음 예제는 setBinaryStream() 메서드를 사용하여 BLOB 데이터 유형에 값을 설정하는 방법을 보여줍니다.

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 InsertingValueForBlob {
    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 ......

MySQL Workbench에서 해당 레코드의 BLOB 값을 확인해 보면, 아래 그림과 같이 이미지가 정상적으로 삽입된 것을 확인할 수 있습니다.

JDBC로 BLOB 데이터 삽입하기 – setBinaryStream()과 setBlob() 메서드 활용 예제

참고 사항

MySQL Connector/J 8.0 이상 버전을 사용한다면 드라이버 클래스명이 com.mysql.cj.jdbc.Driver로 변경되었으므로 이를 사용하는 것이 좋습니다. 또한 대용량 이미지나 파일을 다룰 때는 스트림 길이를 명시적으로 지정하는 setBinaryStream(int, InputStream, long) 변형 메서드를 사용하면 더 안정적으로 처리할 수 있습니다.