最標準的 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!"); }}