第三步,以及接下来的几步,我们来分别编写clob和blob的插入数据库和读出数据库的代码,新建com.test.InsertBlobData.java,顾名思义,它是用来插入blob类型数据的类。代码如下:
- class InsertBlobData{
- private ResultSet rs = null;
- private InitDB idb = null;
- InsertBlobData()
- {
- idb = new InitDB();
- }
- public void insertBlob(String sql1) throws SQLException
- {
- Connection con = idb.getCon();
- try
- {
- con.setAutoCommit(false);// 不设置自动提交
- BLOB blob = null; // 插入空的Blob
- PreparedStatement pstmt = con
- .prepareStatement("insert into cdl_test(sid,img) values(?,empty_blob())");
- pstmt.setString(1, "100");
- pstmt.executeUpdate();
- pstmt.close();
- rs = con.createStatement().executeQuery(sql1);
- while (rs.next())
- {
- System.out.println("rs length is:");
- Oracle.sql.BLOB b = (oracle.sql.BLOB) rs.getBlob("img");
- System.out.println("cloblength is:" + b.getLength());
- File f = new File("d:\\1.jpg"); //1.jpg一张QQ的截图
- System.out.println("file path is:" + f.getAbsolutePath());
- BufferedInputStream in = new BufferedInputStream(
- new FileInputStream(f));
- BufferedOutputStream out = new BufferedOutputStream(b
- .getBinaryOutputStream());
- int c;
- while ((c = in.read()) != -1)
- {
- out.write(c);
- }
- in.close();
- out.close();
- }
- con.commit();
- }
- catch (Exception e)
- {
- con.rollback();// 出错回滚
- e.printStackTrace();
- }
- }
- }
