JAVA連結MYSQL

來源:互聯網
上載者:User

標籤:密碼   use   orm   close   query   java   sql   nal   lin   

1.基本參數

 

   // JDBC 驅動名及資料庫 URL    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";      //localhost:本地    static final String DB_URL = "jdbc:mysql://localhost:3306/mysql";     // 資料庫的使用者名稱與密碼,需要根據自己的設定    static final String USER = "root";    static final String PASS = "123456";

2.注入驅動串連資料庫,zzz_form表進行name檢索,關閉資料庫

    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 name FROM zzz_form";            ResultSet rs = stmt.executeQuery(sql);                    // 展開結果集資料庫            while(rs.next()){                // 通過欄位檢索                String name = rs.getString("name");                myNameList.add(name);                System.out.println(name);            }            // 完成後關閉            rs.close();            stmt.close();            conn.close();        }catch(SQLException se){            // 處理 JDBC 錯誤            System.out.print("處理 JDBC 錯誤");            se.printStackTrace();        }catch(Exception e){            // 處理 Class.forName 錯誤            System.out.print("處理 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();            }        }

說明:

1.匯入庫 mysql-connector-java-5.1.42-bin.jar

 

JAVA連結MYSQL

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.