最規范的 Java MySQL 銜接。本站提示廣大學習愛好者:(最規范的 Java MySQL 銜接)文章只能為提供參考,不一定能成為您想要的結果。以下是最規范的 Java MySQL 銜接正文
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!");
}
}