1,首先建一个足够简单的表imageTable
id varchar(20)
image blob
2,blob入库
拷贝Sunset.jpg图片在C盘根目录下
3,blob出库
id varchar(20)
image blob
2,blob入库
拷贝Sunset.jpg图片在C盘根目录下
1
DriverManager.registerDriver(
new
oracle.jdbc.driver.OracleDriver());
2
Connection conn
=
DriverManager.getConnection(
"
jdbc:oracle:thin:@localhost:1521:beyondduke
"
,
"
duke
"
,
"
duke
"
);
3
conn.setAutoCommit(
false
);
4
BLOB blob
=
null
;
5
PreparedStatement pstmt
=
conn.prepareStatement(
"
insert into imageTable(id,image) values(?,empty_blob())
"
);
6
pstmt.setString(
1
,
"
10001
"
);
7
pstmt.executeUpdate();
8
pstmt.close();
9
pstmt
=
conn.prepareStatement(
"
select content from imageTable where id= ? for update
"
);
10
pstmt.setString(
1
,
"
10001
"
);
11
ResultSet rs
=
pstmt.executeQuery();
12
if
(rs.next()) blob
=
(BLOB) rs.getBlob(
1
);
13
String fileName
=
"
c://Sunset.jpg
"
;
14
File f
=
new
File(fileName);
15
FileInputStream fin
=
new
FileInputStream(f);
16
System.out.println(
"
file size =
"
+
fin.available());
17
pstmt
=
conn.prepareStatement(
"
update imageTable set image=? where id=?
"
);
18
OutputStream out
=
blob.getBinaryOutputStream();
19
byte
[] data
=
new
byte
[(
int
)fin.available()];
20
fin.read(data);
21
out.write(data);
22
out.close();
23
fin.close();
24
25
pstmt.setBlob(
1
,blob);
26
pstmt.setString(
2
,
"
fankai
"
);
27
28
pstmt.executeUpdate();
29
pstmt.close();
30
31
conn.commit();
32
conn.close();
浏览数据库的数据,发现image项中数据大小与图片大小一致,说明入库了!

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

3,blob出库
1
DriverManager.registerDriver(
new
oracle.jdbc.driver.OracleDriver());
2
Connection conn
=
DriverManager.getConnection(
"
jdbc:oracle:thin:@localhost:1521:beyondduke
"
,
"
duke
"
,
"
duke
"
);
conn.setAutoCommit(
false );
3
Statement stmt
=
conn.createStatement();
4
/**/
/* 查询BLOB对象 */
5
ResultSet rs
=
stmt.executeQuery(
"
SELECT content FROM javatest WHERE id='1001'
"
);
6
while
(rs.next())
{
7
/**//* 取出此BLOB对象 */
8
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("image");
9
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("d://Sunset.jpg"));
BufferedInputStream in
= new BufferedInputStream(blob .getBinaryStream());
10
int c;
11
while ((c = in.read()) != -1)
{ out.write(c);
12
}
13
in.close();
14
out.close();
15
rs.close();
16
stmt.close();
17
conn.close();
18
检查D盘根目录,会发现Sunset.jpg文件,跟C盘下是一样的,说明入库出库成功!

2

conn.setAutoCommit(
false );
3

4


5

6



7


8

9


BufferedInputStream in
= new BufferedInputStream(blob .getBinaryStream());
10

11



12

13

14

15

16

17

18


beyondduke 2006-02-14 09:23
发表评论