前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JDBC 2.0中的高级数据类型

JDBC 2.0中的高级数据类型

作者头像
阿新
发布2018-04-11 11:17:10
6030
发布2018-04-11 11:17:10
举报
文章被收录于专栏:c#开发者c#开发者

JDBC 2.0中提供了对SQL3标准中引入的新的数据类型,如Blob(binary large object)、Clob(character large object)、Array 对象、REF(对象参考,object reference)和 UDT(用户定义数据类型,user-defined datatype)等的支持。这些新的数据类型结合在一起,使得数据库设计人员可以创建更丰富的模式,并简化了对复杂数据的处理和持久化。

    例如,我们要向tbl_User表中插入用户的照片,这时就可以使用流将Blob对象导入数据库中:

String sql = "intsert into tbl_User values(?, ?)"; PreparedStatement pstmt = con.prepareStatement(sql) ; File file = new File("C:/images/photo.jpg") ; FileInputStream fis = new FileInputStream(file); pstmt.setString(1, "John"); pstmt.setBinaryStream(2, fis, (int)file.length()); pstmt.executeUpdate(); pstmt.close(); fis.close();

    其中SQL语句的第一个参数为用户名,第二个参数为photo,它是一个Blob型对象。这样在将数据插入数据库之后,我们就可以用程序获取该数据了:

String sql = "select photo from tbl_User where username = ?"; PreparedStatement pstmt = con.prepareStatement(selectSQL) ; pstmt.setString(1, "John"); ResultSet rs = pstmt.executeQuery() ; rs.next(); Blob blob = rs.getBlob("photo") ; ImageIcon icon = new ImageIcon(blob.getBytes(1, (int)blob.length())) ; JLabel photo = new JLabel(icon); rs.close(); pstmt.close();

    类似地,我们也可以对Clob对象进行相应的操作。下面是一个从 ASCII 流中直接将 Clob对象插入数据库中的例子:

String sql = "insert into tbl_Articles values(?,?)"; PreparedStatement pstmt = con.prepareStatement(sql) ; File file = new File("C:/data/news.txt") ; FileInputStream fis = new FileInputStream(file); pstmt.setString(1, "Iraq War"); pstmt.setAsciiStream(2, fis, (int)file.length()); pstmt.executeUpdate(); pstmt.close(); fis.close();

    同样,我们也可以用类似的方法将Clob对象从数据库中取出:

String sql = "select content from tbl_Articles where title = ?"; PreparedStatement pstmt = con.prepareStatement(sql) ; pstmt.setString(1, "Iraq War"); ResultSet rs = pstmt.executeQuery() ; rs.next() ; Clob clob = rs.getClob("content") ; InputStreamReader in = new InputStreamReader(clob.getAsciiStream()) ; JTextArea text = new JTextArea(readString(in)) ; rs.close(); pstmt.close();

(T111)

本文选自飞思图书《精通Java核心技术》

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2005-01-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档