Java鏈接Oracle數據庫

package com.db;  
      
    import java.sql.Connection;  
    import java.sql.DriverManager;  
    import java.sql.PreparedStatement;  
    import java.sql.ResultSet;  
      
    public class DBConnection {  
        // 鏈接Oracle數據庫  
        public void OracleConnection() {  
            Connection con = null;  
            PreparedStatement pre = null;  
            ResultSet rs = null;  
      
            try {  
                // 1. 加載Oracle驅動程序  
                Class.forName("oracle.jdbc.driver.OracleDriver");  
                  
                // 2. 設置Oracle數據庫基本信息  
                String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";  
                String user = "scott";  
                String password = "goodluck";  
      
                // 2. 獲取鏈接  
                con = DriverManager.getConnection(url, user, password);  
                System.out.println("----> Connection Success!");  
      
                // 3. 執行SQL語句  
                String sql = "SELECT * FROM EMP";  
                pre = con.prepareStatement(sql);  
      
                // 4. 獲取結果集  
                rs = pre.executeQuery();  
                while (rs.next()) {  
                    System.out.println("編號:" + rs.getString("empno")   
                                    + ";姓名:" + rs.getString("ename")  
                                    + "; 工做:" + rs.getString("job")  
                                    + "; 領導:" + rs.getString("mgr")  
                                    + "; 僱傭日期:" + rs.getString("hiredate")  
                                    + "; 工資:" + rs.getString("sal")  
                                    + "; 獎金:" + rs.getString("comm")  
                                    + "; 部門:" + rs.getString("deptno"));  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            } finally {  
                try {  
                    if (rs != null)  
                        rs.close();  
                    if (pre != null)  
                        pre.close();  
                    if (con != null)  
                        con.close();  
                    System.out.println("----> Connection End <-----");  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
      
        public static void main(String[] args) {  
            DBConnection db = new DBConnection();  
            db.OracleConnection();  
        }  
    }
相關文章
相關標籤/搜索