メモ - JDBCでBLOBの読み書きを行う。Advertisementテーブル
blob_testテーブルを作成(実験ではOracleを利用)
create table blob_test( id char(1) primary key, obj blob ); ソースコード
insert
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class BlobInsert{
public static void main(String[] args) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@127.0.0.1:1521:sample",
"user",
"pass");
File file = new File("c:\\blob.txt");
String sql = "insert into blob_test(id, obj)VALUES('1', ?)";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setBinaryStream(1, new FileInputStream(file), (int)file.length());
int result = stmt.executeUpdate();
stmt.close();
}
}
select
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class BlobRead{
public static void main(String[] args) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@127.0.0.1:1521:sample",
"user",
"pass");
Statement state = con.createStatement();
String sql = "select * from blob_test";
boolean result = state.execute(sql);
ResultSet rs = state.getResultSet();
while(rs.next()) {
String id = rs.getString(1);
Blob blob = rs.getBlob(2);
InputStream in = blob.getBinaryStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytes;
byte b[] = new byte[4096];
while ((bytes = in.read(b)) != -1){
baos.write(b, 0, bytes);
}
System.out.println(id + ":" + baos.toString());
}
con.close();
}
}
Advertisement |
ショートカット・634・このカテゴリのトップページに戻る ・634labs UIコレクションギャラリー サイト検索Y!ログール |