第五步,新建com.test.ReadBlobData.java,用于读取blob类型的数据,代码如下:
- class ReadBlobData
- {
- private ResultSet rs = null;
- private InitDB idb = null;
- ReadBlobData()
- {
- idb = new InitDB();
- }
- public void getBlob(String sql2) throws SQLException
- {
- Connection con = idb.getCon();
- con.setAutoCommit(false);
- try
- {
- System.out.println("sq2 is:" + sql2);
- System.out.println("stmt is:" + con);
- rs = con.createStatement().executeQuery(sql2);
- while (rs.next())
- {
- System.out.println("rs length is:");
- Blob b = (Blob) rs.getBlob("img");
- File f = new File("D:\\1.jpg");
- FileOutputStream fos = new FileOutputStream(f);
- InputStream is = b.getBinaryStream();// 读出数据后转换为二进制流
- byte[] data = new byte[1024];
- while (is.read(data) != -1)
- {
- fos.write(data);
- }
- fos.close();
- is.close();
- }
- con.commit();// 正式提交
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- // rs.close();
- }
- }
- }
