관리자 글쓰기
JDBC BLOB 타입 데이터 입/출력
2017. 1. 17. 17:40 - 개발 새발


BLOB 데이터 삽입

File inputBinaryFile = null;

FileInputStream inputFileInputStream =null;

BLOB blob = null;

int chunkSize=0, bytesRead = 0, bytesWritten=0;

conn.setAutoCommit(false);

inputBinaryFile = new File("C:\\Users\\JYH\\Documents\\카카오톡 받은 파일\\바꾸기.jpg");

inputFileInputStream = new FileInputStream(inputBinaryFile);

String sql = "INSERT INTO TEST_BLOB(TNAME, CONTENTS) VALUES('22131231',EMPTY_BLOB())";

PreparedStatement pstmt=conn.prepareStatement(sql);

int result =  pstmt.executeUpdate();

sql = "SELECT TNAME,CONTENTS FROM TEST_BLOB";

pstmt=conn.prepareStatement(sql);

ResultSet rs = pstmt.executeQuery();

rs.next();

blob = ((OracleResultSet)rs).getBLOB("CONTENTS");

chunkSize = blob.getChunkSize();

byte[] byteBuffer = new byte[chunkSize];

long position = 1;

while((bytesRead = inputFileInputStream.read(byteBuffer))!=-1){

bytesWritten = blob.putBytes(position, byteBuffer,bytesRead);

position += bytesRead;

}

inputFileInputStream.close();

conn.commit();

rs.close();

pstmt.close();




BLOB 데이터 출력


FileOutputStream fos =null;

BLOB blob = null;

int chunkSize=0;


String sql = "SELECT TNAME,CONTENTS FROM TEST_BLOB";

PreparedStatement pstmt=conn.prepareStatement(sql);

ResultSet rs = pstmt.executeQuery();

rs.next();

blob = (BLOB) rs.getBlob("CONTENTS");

chunkSize = blob.getChunkSize();

byte[] byteBuffer = new byte[chunkSize];

byteBuffer = blob.getBytes(1,(int)blob.length());

fos = new FileOutputStream("C:\\Users\\JYH\\Documents\\카카오톡 받은 파일\\바꾸기1.jpg");

fos.write(byteBuffer, 0, (int)byteBuffer.length);



'코딩 > Java' 카테고리의 다른 글

[JAVA] SMTP 이용하기  (0) 2017.01.14
[JAVA] 비동기 채널 API  (0) 2017.01.13
[JavaFX] ComboBox, RadioButton  (0) 2017.01.12
[NIO]TCP 비동기/블로킹/넌블로킹의 차이  (0) 2017.01.05
[NIO]TCP 비동기 채널 - 비동기 소켓 채널  (0) 2017.01.05