Oracle JDBC 標准連接實例


Oracle JDBC 標准連接實例

        // 創建一個數據庫連接
        Connection con = null; // 創建預編譯語句對象,一般用PreparedStatement不用Statement
        PreparedStatement pre = null; // 創建一個結果集對象
        ResultSet result = null; try { // 加載Oracle驅動程序
            Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("開始嘗試連接數據庫!"); // 127.0.0.1是本機地址,orcl是數據庫名
            String url = "jdbc:oracle:" + "thin:@192.168.127.10:1521:orcl"; // 用戶名,系統默認的賬戶名
            String user = "CTRR"; // 安裝時選設置的密碼
            String password = "123456"; // 獲取連接
            con = DriverManager.getConnection(url, user, password); System.out.println("連接成功!"); // 預編譯語句,“?”代表參數
            String sql = "select * from LEVEL4 where LEVEL4_CODE like ?"; pre = con.prepareStatement(sql);// 實例化預編譯語句 // 設置參數,前面的1表示參數的索引,而不是表中列名的索引
            pre.setString(1, "%3AL34812ABAA%"); // 執行查詢,注意括號中不需要再加參數
            result = pre.executeQuery(); while (result.next()) // 當結果集不為空時
                System.out.println("LEVEL4_CODE: " + result.getString("LEVEL4_CODE")); } catch (Exception e) { e.printStackTrace(); } finally { try { // 逐一將上面的幾個對象關閉,因為不關閉的話會影響性能、並且占用資源 // 注意關閉的順序,最后使用的最先關閉
                if (result != null) result.close(); if (pre != null) pre.close(); if (con != null) con.close(); System.out.println("數據庫連接已關閉!"); } catch (Exception e) { e.printStackTrace(); } }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM