java讀取影像檔存入oracle中blob欄位原始碼

來源:互聯網
上載者:User

資料庫:oracle 10G XE

資料來源驅動:jdbc12.jar

檔案名稱:WriteBlob

資料庫中建立一個為clobtest的表,內有兩個欄位,name (varchar2(20)),content(blob)。

1package dbdriver;
2
3/** *//**
4 * 2008-09-28
5 * @author duduli
6 * email: lxyzj2000@gmail.com
7 */
8import java.sql.*;
9import java.io.*;
10import oracle.sql.*;
11
12public class WriteBlob {
13
14  public static void main(String[] args) {
15    try {
16      String fName2 = "";
17      String fileName = "E:\\jianxin.bmp";
18//E盤下遊個jianxin.bmp的影像檔
19      File f = new File(fileName);
20      String fName = f.getName();
21      int i = fName.lastIndexOf('.');
22      if (i > 0 && i < fName.length()-1){
23          fName2 = fName.substring(0,i);
24        }
25      System.out.println(fName2);
26//獲得檔案名稱,出去尾碼的檔案名稱。
27      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
28      Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:XE", "system", "duduli  ");
29      conn.setAutoCommit(false);
30      BLOB blob = null;
31      PreparedStatement pstmt = conn.prepareStatement("insert into blobtest(name,content) values(?,empty_blob())");
32      pstmt.setString(1, fName2);
33      pstmt.executeUpdate();
34      pstmt.close();
35      pstmt = conn.prepareStatement("select content from blobtest where name= ? for update");
36      pstmt.setString(1, fName2);
37      ResultSet rset = pstmt.executeQuery();
38      if (rset.next()) {
39        blob = (BLOB) rset.getBlob(1);
40      }
41
42      FileInputStream fin = new FileInputStream(f);
43      System.out.println("file size = " + fin.available());
44      pstmt = conn.prepareStatement("update blobtest set content=? where name=?");
45      OutputStream out = blob.getBinaryOutputStream();
46      byte[] data = new byte[(int) fin.available()];
47      fin.read(data);
48      out.write(data);
49      fin.close();
50      out.close();
51      pstmt.setBlob(1, blob);
52      pstmt.setString(2, fName2);
53      pstmt.executeUpdate();
54      pstmt.close();
55      conn.commit();
56      conn.close();
57        } catch (SQLException e) {
58          System.err.println(e.getMessage());
59          e.printStackTrace();
60        } catch (IOException e) {
61          System.err.println(e.getMessage());
62        }
63  }
64}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.