最標準的 Java MySQL 串連,javamysql串連

來源:互聯網
上載者:User

最標準的 Java MySQL 串連,javamysql串連

package com.runoob.test; import java.sql.*; public class MySQLDemo {     // JDBC 驅動名及資料庫 URL    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";      static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB";     // 資料庫的使用者名稱與密碼,需要根據自己的設定    static final String USER = "root";    static final String PASS = "123456";     public static void main(String[] args) {        Connection conn = null;        Statement stmt = null;        try{            // 註冊 JDBC 驅動            Class.forName("com.mysql.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);                System.out.print(", 網站 URL: " + url);                System.out.print("\n");            }            // 完成後關閉            rs.close();            stmt.close();            conn.close();        }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();            }        }        System.out.println("Goodbye!");    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.