DriverManager 註冊。但 Microsoft JVM (IE Applet) 無法正確初始化。System.getProperty().load(...) 讀取屬性檔中的 jdbc.driver,優點是更換資料庫無需改動 Java 程式碼。建議:一般環境用 (1);Applet 或特殊環境用 (3);需動態切換資料庫用 (2)。
標準 JDBC 2.0 無法直接對 BLOB 寫入二進位檔案,會拋出 IO Exception 而非 SQL Exception。正確做法有二:
CREATE TABLE tb_file(name VARCHAR(20), detail LONG RAW);
File file = new File("aaa.gif");
int len = (int) file.length();
InputStream fin = new FileInputStream(file);
PreparedStatement pstmt = con.prepareStatement("INSERT INTO tb_file VALUES('aaa.gif', ?)");
pstmt.setBinaryStream(1, fin, len);
pstmt.executeUpdate();
CREATE TABLE tb_file(name VARCHAR(20), detail BLOB);
con.setAutoCommit(false);
stmt.executeUpdate("INSERT INTO tb_file VALUES('aaa.gif', EMPTY_BLOB())");
ResultSet rs = stmt.executeQuery("SELECT detail FROM tb_file WHERE name='aaa.gif' FOR UPDATE");
if (rs.next()) {
Blob blob = rs.getBlob(1);
OutputStream out = ((oracle.sql.BLOB)blob).getBinaryOutputStream();
byte[] buf = new byte[((oracle.sql.BLOB)blob).getBufferSize()];
InputStream fin = new FileInputStream(file);
int n;
while ((n = fin.read(buf)) != -1) out.write(buf, 0, n);
fin.close(); out.close(); con.commit();
}
讀取時亦須用 blob.getBinaryStream(),不可用 rs.getBinaryStream()。
Oracle 明確不支援伺服器端游標捲動,JDBC 2.0 的 TYPE_SCROLL_INSENSITIVE 實際是將全部結果集緩存在客戶端記憶體。查詢大量資料時會導致 OOM。大量資料查詢請務必使用唯讀、順向游標,捨棄捲動功能。