首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> MySQL 資料庫 >> MySQL 綜合教學

Java 程式透過 JDBC 連接 MySQL 實現增刪改查完整範例

     編輯:MySQL 綜合教學

Java 程式透過 JDBC 連接 MySQL 實現增刪改查完整範例

承接上篇 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) {}
        }
    }
}

專案配置關鍵步驟

  1. 右鍵專案 → Build Path → Configure Build Path → Libraries → Add External JARs,加入 MySQL JDBC jar。
  2. 確認 Referenced Libraries 出現該 jar。
  3. Run As → Java Application,觀察 Console 輸出。

常見坑點提醒

  • URL 格式:jdbc:mysql://host:port/dbname,勿漏掉 //。
  • 欄位型別對應:getInt 對應 INT,getString 對應 VARCHAR/CHAR,getDate 對應 DATE/DATETIME。
  • 生產環境請使用 PreparedStatement 防 SQL 注入,並配置連線池(如 HikariCP)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved