1.package test;
2.
3.import java.io.BufferedInputStream;
4.import java.io.FileInputStream;
5.import java.io.PrintStream;
6.import java.sql.Connection;
7.import java.sql.DriverManager;
8.import java.sql.ResultSet;
9.import java.sql.SQLException;
10.import java.sql.Statement;
11.
12.public class Test {
13. private Connection conn;
14.
15. /**
16. * 得到一個資料庫的連接
17. *
18. * @return 返加Connection物件
19. */
20. public Connection getConnection() {
21. try {
22. Class.forName("oracle.jdbc.driver.OracleDriver");
23. conn = DriverManager.getConnection(
24. "jdbc:oracle:thin:@localhost:1521:lyx", "scott", "tiger");
25. } catch (ClassNotFoundException e) {
26. // TODO Auto-generated catch block
27. e.printStackTrace();
28. } catch (SQLException e) {
29. // TODO Auto-generated catch block
30. e.printStackTrace();
31. }
32. return conn;
33. }
34.
35. /**
36. * 向表中插入圖片
37. *
38. * @param path圖片所在的路徑
39. * @return 整形 判斷成功或失敗
40. */
41. public int insertImage(String path) throws Exception {
42. int i = 0;
43. Statement st = null;
44. ResultSet rs = null;
45. conn=this.getConnection();
46.
47. conn.setAutoCommit(false);//設置資料庫為不自動提交,必須的一步
48. st = conn.createStatement();
49. //先插入一個空物件,這裡我調用了Empty_BLOB()函數
50. i = st.executeUpdate("insert into image (id,image) values (seq1.nextval,Empty_BLOB())");
51. //以行的方式鎖定
52. rs = st.executeQuery("select image from image where id=(select max(id) from image) for update");
53. if (rs.next()) {
54. //得到流
55. oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1);
56. //從得到的低級流構造一個高級流
57. PrintStream ps = new PrintStream(blob.getBinaryOutputStream());
58. BufferedInputStream bis = new BufferedInputStream(
59. new FileInputStream(path));
60. byte[] buff = new byte[1024];
61. int n = 0;
62. //從輸入到輸出
63. while ((n = bis.read(buff)) != -1) {
64. ps.write(buff, 0, n);
65.
66. }
67. //清空流的緩存
68. ps.flush();
69.
 
arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()