通過JDBC讀取Blob數(shù)據(jù),演示代碼
1.
2.import java.io.File; 3.import java.io.FileOutputStream; 4.import java.io.IOException; 5.import java.io.InputStream; 6.import java.io.OutputStream; 7.import java.sql.Connection; 8.import java.sql.DriverManager; 9.import java.sql.ResultSet; 10.import java.sql.Statement; 11.
12.public class JDBC { 13.// public static void main(String[] args) throws Exception { 14.// // 寫入BLOB數(shù)據(jù) 15.// 16.// // 得到數(shù)據(jù)庫連接 17.// Class.forName("Oracle.jdbc.driver.OracleDriver"); 18.// 19.// Connection con = DriverManager.getConnection( 20.// 21.// "jdbc:Oracle:thin:@192.168.0.68:1521:myOracle", "my", "123"); 22.// 23.// // 處理事務(wù) 24.// 25.// con.setAutoCommit(false); 26.// 27.// Statement st = con.createStatement(); 28.// 29.// // 用for update方式鎖定數(shù)據(jù)行 30.// 31.// ResultSet rs = st.executeQuery( 32.// 33.// "select content from user_content where id = 2 for update"); 34.// 35.// if (rs.next()) { 36.// 37.// // 得到j(luò)ava.sql.Blob對象,然后Cast為Oracle.sql.BLOB 38.// 39.// Oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1); 40.// 41.// // 到數(shù)據(jù)庫的輸出流 42.// 43.// OutputStream outStream = blob.getBinaryOutputStream(); 44.// 45.// // 這里用一個文件模擬輸入流 46.// 47.// File file = new File("d:\\proxy.txt"); 48.// 49.// InputStream fin = new FileInputStream(file); 50.// 51.// // 將輸入流寫到輸出流 52.// 53.// byte[] b = new byte[blob.getBufferSize()]; 54.// 55.// int len = 0; 56.// 57.// while ((len = fin.read(b)) != -1) { 58.// 59.// outStream.write(b, 0, len); 60.// 61.// // blob.putBytes(1,b); 62.// 63.// } 64.// 65.// // 依次關(guān)閉(注意順序) 66.// 67.// fin.close(); 68.// 69.// outStream.flush(); 70.// 71.// outStream.close(); 72.// 73.// con.commit(); 74.// 75.// con.close(); 76.// } 77.// } 78.
79. public static void main(String[] args) throws Exception { 80. // 讀取BLOB數(shù)據(jù) 81.
82. Class.forName("Oracle.jdbc.driver.OracleDriver"); 83.
84. Connection con = DriverManager.getConnection(
85.
86. "jdbc:Oracle:thin:@192.168.0.68:1521:myOracle", "my", "123"); 87.
88. con.setAutoCommit(false); 89.
90. Statement st = con.createStatement();
91.
92. // 這里的SQL語句不再需要”for update” 93.
94. ResultSet rs = st.executeQuery(
95.
96. "select content from user_content where id = 2"); 97.
98. if (rs.next()) { 99.
100. java.sql.Blob blob = rs.getBlob(1); 101.
102. InputStream ins = blob.getBinaryStream();
103.
104. // 用文件模擬輸出流 105.
106. File file = new File("d:\\output.txt"); 107.
108. OutputStream fout = new FileOutputStream(file); 109.
110. // 下面將BLOB數(shù)據(jù)寫入文件 111.
112. byte[] b = new byte[1024]; 113.
114. int len = 0; 115.
116. while ((len = ins.read(b)) != -1) { 117.
118. fout.write(b, 0, len); 119.
120. }
121.
122. // 依次關(guān)閉 123.
124. fout.close();
125.
126. ins.close();
127.
128. con.commit();
129.
130. con.close();
131. }
132. }
133.}
本文出自:億恩科技【mszdt.com】
服務(wù)器租用/服務(wù)器托管中國五強!虛擬主機域名注冊頂級提供商!15年品質(zhì)保障!--億恩科技[ENKJ.COM]
|