首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

Java JDBC 連接 MySQL 完整入門:從加載驅動到預處理查詢的標準化代碼模板

     編輯:MySQL 資料庫相關知識

一、 依賴準備



    mysql
    mysql-connector-java
    8.0.33  

驅動類名差異:

  • 5.x:com.mysql.jdbc.Driver
  • 8.x:com.mysql.cj.jdbc.Driver

二、 核心工具類封裝

public class JdbcUtil {
    private static final String URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";  // 8.x

    static {
        try { Class.forName(DRIVER); } catch (ClassNotFoundException e) { throw new ExceptionInInitializerError(e); }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try { if (rs != null) rs.close(); } catch (SQLException ignore) {}
        try { if (stmt != null) stmt.close(); } catch (SQLException ignore) {}
        try { if (conn != null) conn.close(); } catch (SQLException ignore) {}
    }
}

三、 標準查詢模板(預處理語句)

public List queryUsers() {
    String sql = "SELECT id, username, email FROM users WHERE status = ?";
    List list = new ArrayList<>();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = JdbcUtil.getConnection();
        ps = conn.prepareStatement(sql);
        ps.setInt(1, 1);  // 參數綁定,防注入
        rs = ps.executeQuery();
        while (rs.next()) {
            User u = new User();
            u.setId(rs.getLong("id"));
            u.setUsername(rs.getString("username"));
            u.setEmail(rs.getString("email"));
            list.add(u);
        }
    } catch (SQLException e) {
        e.printStackTrace();  // 生產環境用日誌框架
    } finally {
        JdbcUtil.close(conn, ps, rs);
    }
    return list;
}

四、 事務控制模板

public void transfer(Long fromId, Long toId, BigDecimal amount) {
    Connection conn = null;
    try {
        conn = JdbcUtil.getConnection();
        conn.setAutoCommit(false);  // 開啟事務

        // 扣款
        try (PreparedStatement ps = conn.prepareStatement("UPDATE account SET balance = balance - ? WHERE id = ?")) {
            ps.setBigDecimal(1, amount);
            ps.setLong(2, fromId);
            ps.executeUpdate();
        }
        // 入賬
        try (PreparedStatement ps = conn.prepareStatement("UPDATE account SET balance = balance + ? WHERE id = ?")) {
            ps.setBigDecimal(1, amount);
            ps.setLong(2, toId);
            ps.executeUpdate();
        }

        conn.commit();
    } catch (SQLException e) {
        if (conn != null) try { conn.rollback(); } catch (SQLException ignore) {}
        throw new RuntimeException("Transfer failed", e);
    } finally {
        if (conn != null) try { conn.setAutoCommit(true); conn.close(); } catch (SQLException ignore) {}
    }
}

五、 連接池升級(生產必備)

手動獲取連接性能差、易洩漏。引入 HikariCP(Spring Boot 默認):


    com.zaxxer
    HikariCP
    5.0.1
// 單例 DataSource
HikariConfig config = new HikariConfig();
config.setJdbcUrl(URL);
config.setUsername(USER);
config.setPassword(PASSWORD);
config.setMaximumPoolSize(20);
config.setMinimumIdle(5);
DataSource ds = new HikariDataSource(config);

// 使用
try (Connection conn = ds.getConnection()) { /* ... */ }

六、 常見坑點速查

七、 總結

Java 操作 MySQL 標準化路徑:驅動加載 → 連接池 → 預處理語句參數綁定 → try-with-resources 自動關閉 → 事務邊界明確。新項目直接上 HikariCP + 8.x 驅動 + serverTimezone=UTC + utf8mb4,拒絕手動 DriverManager.getConnection 與字符串拼接 SQL。掌握此模板,應對 90% 單機業務查詢與事務場景綽綽有餘。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
問題解決
ClassNotFoundException檢查 maven 依賴範圍非 provided、驅動版本匹配 MySQL 版本
Communications link failure檢查 host/port、防火牆、MySQL bind-address、driver 類名
Public Key Retrieval is not allowedURL 加 allowPublicKeyRetrieval=true(8.0+)
時區錯誤URL 加 serverTimezone=UTC 或 Asia/Shanghai
中文亂碼URL characterEncoding=utf8、表/庫 utf8mb4、連接 SET NAMES utf8mb4