写入Oracle Blob字段
读取oracle Blob字段
/**
* 插入Blob字段
*/
public static void insertBlobField(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
String url = "jdbc:oracle:thin:@192.168.8.100:1521:ORCL";
String username = "shouyao";
String password = "shouyao";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username, password);
conn.setAutoCommit(false);
stmt = conn.createStatement();
stmt.execute("insert into a_blob_test(id,picture) values(1,empty_blob())");
rs = stmt.executeQuery("select t.id,t.picture from a_blob_test t where t.id = 1 for update");
File f1 = new File("E:\\hel\\MyEclipse 10.0\\druggist\\code\\src\\test\\test.jpg");
FileInputStream fis = new FileInputStream(f1);
OutputStream os = null;
if(rs.next()){
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(2);
os = blob.getBinaryOutputStream();
byte[] b = new byte[(int) f1.length()];
fis.read(b);
os.write(b);
os.flush();
}
os.close();
conn.commit();
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
读取oracle Blob字段
/**
* 查询Blob字段存储的图片文件,并输出
*/
public static void queryBlobField(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String url = "jdbc:oracle:thin:@192.168.8.100:1521:ORCL";
String username = "shouyao";
String password = "shouyao";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
rs = stmt.executeQuery("select t.id,t.picture from a_blob_test t where t.id = 1");
//文件保存的路径
File f1 = new File("E:\\hel\\MyEclipse 10.0\\druggist\\code\\src\\test\\test1.jpg");
FileOutputStream fos = new FileOutputStream(f1);
InputStream is = null;
if(rs.next()){
Blob blob = rs.getBlob(2);
is = blob.getBinaryStream();
int len =0;
byte[] b = new byte[1024];
while((len = is.read(b)) != -1){
fos.write(b,0,len);
}
}
fos.close();
is.close();
rs.close();
stmt.close();
conn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}