例如,我们要向tbl_User表中插入用户的照片,这时就可以使用流将Blob对象导入数据库中:
String sql = "intsert into tbl_User values(?, ?)"; PreparedStatement pstmt = con.prepareStatement(sql) ; File file = new File("C:/images/photo.jpg") ; pstmt.setString(1, "John"); pstmt.executeUpdate(); pstmt.close(); |
其中SQL语句的第一个参数为用户名,第二个参数为photo,它是一个Blob型对象。这样在将数据插入数据库之后,我们就可以用程序获取该数据了:
String sql = "select photo from tbl_User where username = ?"; PreparedStatement pstmt = con.prepareStatement(selectSQL) ; pstmt.setString(1, "John"); rs.next(); ImageIcon icon = new ImageIcon(blob.getBytes(1, (int)blob.length())) ; rs.close(); |
类似地,我们也可以对Clob对象进行相应的操作。下面是一个从 ASCII 流中直接将 Clob对象插入数据库中的例子:
String sql = "insert into tbl_Articles values(?,?)"; PreparedStatement pstmt = con.prepareStatement(sql) ; File file = new File("C:/data/news.txt") ; pstmt.setString(1, "Iraq War"); pstmt.executeUpdate(); pstmt.close(); |
同样,我们也可以用类似的方法将Clob对象从数据库中取出:
String sql = "select content from tbl_Articles where title = ?"; PreparedStatement pstmt = con.prepareStatement(sql) ; pstmt.setString(1, "Iraq War"); rs.next() ; InputStreamReader in = new InputStreamReader(clob.getAsciiStream()) ; JTextArea text = new JTextArea(readString(in)) ; rs.close(); |