Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Kết nối MySQL từ Java (JDBC): Cổng mặc định 3306 trên localhost

Để kết nối MySQL từ Java, dùng JDBC driver với URL chứa host, port (mặc định 3306), database name và các tham số kết nối.

URL kết nối chuẩn

jdbc:mysql://localhost:3306/ten_database?useSSL=false&serverTimezone=UTC
  • localhost: Host (hoặc IP).
  • 3306: Port mặc định MySQL.
  • ten_database: Tên schema.
  • useSSL=false: Tắt SSL (dev local). Production nên bật SSL.
  • serverTimezone=UTC: Tránh warning timezone (MySQL 8.0+).

Ví dụ Java hoàn chỉnh

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MySQLConnection {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/sample?useSSL=false&serverTimezone=UTC";
        String user = "root";
        String password = "123456";
        
        try (Connection con = DriverManager.getConnection(url, user, password)) {
            if (con != null) {
                System.out.println("MySQL connection successful on port 3306!");
                // Thực hiện query ở đây
            }
        } catch (SQLException e) {
            System.err.println("Connection failed: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Chuẩn bị

  1. Thêm dependency MySQL Connector/J (Maven/Gradle):
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.3.0</version> <!-- hoặc mới nhất -->
</dependency>
  1. Đảm bảo MySQL server chạy và lắng nghe port 3306.
  2. User 'root' có quyền kết nối từ localhost (mặc định có).

Kết quả chạy

MySQL connection successful on port 3306!

Best Practices

  • Dùng try-with-resources (Java 7+) để tự đóng connection.
  • Dùng HikariCP connection pool cho ứng dụng production.
  • Không hardcode password — dùng config file / environment variable.
  • PreparedStatement cho mọi query có tham số (chống SQL Injection).