承接上篇 MyEclipse 連線配置,本文展示一個完整的 Java 類別,涵蓋載入驅動、建立連線、建表、插入、查詢、關閉資源。
package link;
import java.sql.*;
public class JDBCTest {
public static Connection getConnection() throws SQLException, ClassNotFoundException {
// 1. 載入驅動
Class.forName("com.mysql.jdbc.Driver");
// 2. 連線參數(請改為你的實際值)
String url = "jdbc:mysql://localhost:3306/your_db";
String username = "root";
String password = "your_password";
// 3. 建立連線
return DriverManager.getConnection(url, username, password);
}
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
con = getConnection();
stmt = con.createStatement();
// 建表(若不存在)
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS person (" +
"id INT PRIMARY KEY AUTO_INCREMENT, " +
"name VARCHAR(20) NOT NULL, " +
"score INT NOT NULL)");
// 插入測試資料
stmt.executeUpdate("INSERT INTO person (name, score) VALUES ('Alice', 95)");
stmt.executeUpdate("INSERT INTO person (name, score) VALUES ('Bob', 87)");
stmt.executeUpdate("INSERT INTO person (name, score) VALUES ('Cindy', 91)");
// 查詢並顯示
rs = stmt.executeQuery("SELECT * FROM person");
System.out.println("ID\tName\tScore");
System.out.println("-------------------");
while (rs.next()) {
System.out.println(rs.getInt("id") + "\t" +
rs.getString("name") + "\t" +
rs.getInt("score"));
}
} catch (ClassNotFoundException e) {
System.err.println("驅動載入失敗: " + e.getMessage());
} catch (SQLException e) {
System.err.println("SQL 執行錯誤: " + e.getMessage());
} finally {
// 關閉資源(逆序)
try { if (rs != null) rs.close(); } catch (SQLException ignored) {}
try { if (stmt != null) stmt.close(); } catch (SQLException ignored) {}
try { if (con != null) con.close(); } catch (SQLException ignored) {}
}
}
}
Referenced Libraries 出現該 jar。jdbc:mysql://host:port/dbname,勿漏掉 //。getInt 對應 INT,getString 對應 VARCHAR/CHAR,getDate 對應 DATE/DATETIME。PreparedStatement 防 SQL 注入,並配置連線池(如 HikariCP)。