>>建立表create table blob_table(
id number primary key,
blob_cl blob not null
);
insert into blob_table values(1,to_blob('11111000011111'));
commit;
select * from blob_table;
update blob_table
set blob_cl=to_blob('110010000110011')
where id=1;
delete from blob_table where id=1;
commit;java
package
test;
import
java.io.BufferedInputStream;
import
java.io.FileInputStream;
import
java.io.PrintStream;
import
java.sql.Connection;
import
java.sql.DriverManager;
import
java.sql.ResultSet;
import
java.sql.SQLException;
import
java.sql.Statement;
public
class
Test {
private
Connection conn;
/**
* 獲得一個數據庫的鏈接
*
* @return 返加Connection對象
*/
public
Connection getConnection() {
try
{
Class.forName(
"oracle.jdbc.driver.OracleDriver"
);
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:lyx"
,
"scott"
,
"tiger"
);
}
catch
(ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch
(SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return
conn;
}
/**
* 向表中插入圖片
*
* @param path圖片所在的路徑
* @return 整形 判斷成功或失敗
*/
public
int
insertImage(String path)
throws
Exception {
int
i =
0
;
Statement st =
null
;
ResultSet rs =
null
;
conn=
this
.getConnection();
conn.setAutoCommit(
false
);
//設置數據庫爲不自動提交,必須的一步
st = conn.createStatement();
//先插入一個空對象,這裏我調用了Empty_BLOB()函數
i = st
.executeUpdate(
"insert into image (id,image) values (seq1.nextval,Empty_BLOB())"
);
//以行的方式鎖定
rs = st
.executeQuery(
"select image from image where id=(select max(id) from image) for update"
);
if
(rs.next()) {
//獲得流
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(
1
);
//從獲得的低級流構造一個高級流
PrintStream ps =
new
PrintStream(blob.getBinaryOutputStream());
BufferedInputStream bis =
new
BufferedInputStream(
new
FileInputStream(path));
byte
[] buff =
new
byte
[
1024
];
int
n =
0
;
//從輸入到輸出
while
((n = bis.read(buff)) != -
1
) {
ps.write(buff,
0
, n);
}
//清空流的緩存
ps.flush();
//關閉流,注意必定要關
ps.close();
bis.close();
}
rs.close();
st.close();
conn.close();
return
i;
}
public
static
void
main(String[] args)
throws
Exception {
Test test=
new
Test();
test.insertImage(
"e:\\3.jpg"
);
System.out.println(
"OK"
);
}
}