1. 程式人生 > >JAVA 連線資料庫的步驟

JAVA 連線資料庫的步驟

第一步:資料庫驅動和資料量地址基本資訊。

// MySQL 8.0 以下版本 - JDBC 驅動名及資料庫 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB";
 
    // MySQL 8.0 以上版本 - JDBC 驅動名及資料庫 URL
    //static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
    //static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB?useSSL=false&serverTimezone=UTC";
 
 
    // 資料庫的使用者名稱與密碼,需要根據自己的設定
    static final String USER = "root";
    static final String PASS = "123456";
 

第二步:註冊驅動

  // 註冊 JDBC 驅動
      Class.forName(JDBC_DRIVER);
 

第三步:開啟連線

          // 開啟連結
            System.out.println("連線資料庫...");
            conn = DriverManager.getConnection(DB_URL,USER,PASS);

第四步:執行查詢

          // 執行查詢
            System.out.println(" 例項化Statement物件...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT id, name, url FROM websites";
            ResultSet rs = stmt.executeQuery(sql);

第五步:顯示查詢結果集

        // 展開結果集資料庫
            while(rs.next()){
                // 通過欄位檢索,假設如下三個欄位為查詢欄位
                int id  = rs.getInt("id");
                String name = rs.getString("name");
                String url = rs.getString("url");
    
                // 輸出資料
                System.out.print("ID: " + id);
                System.out.print(", NAME: " + name);
                System.out.print(", URL: " + url);
                System.out.print("\n");

第六步:完成後關閉

            // 完成後關閉
            rs.close();
            stmt.close();
            conn.close();

第七步:處理錯誤

//處理錯誤或者異常
try{
..............
}catch(SQLException se){
            // 處理 JDBC 錯誤
            se.printStackTrace();
        }catch(Exception e){
            // 處理 Class.forName 錯誤
            e.printStackTrace();
        }finally{
            // 關閉資源
            try{
                if(stmt!=null) stmt.close();
            }catch(SQLException se2){
            }// 什麼都不做
            try{
                if(conn!=null) conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }

&n