พื้นฐานการเชื่อมต่อ MySQL จาก Java
ใช้ JDBC (Java Database Connectivity) Driver: mysql-connector-j (ใหม่) หรือ mysql-connector-java (เก่า)
JDBC URL Format
jdbc:mysql://[host][:port]/[database][?properties]
องค์ประกอบสำคัญ
- Host: localhost / 127.0.0.1 / IP Address / Hostname
- Port: 3306 (Default MySQL Port)
- Database: ชื่อ Schema/Database
- Properties: Connection Parameters (SSL, Timezone, etc.)
ตัวอย่างโค้ด Java 完整
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnectionExample {
public static void main(String[] args) {
// JDBC URL กำหนด Port 3306 โดยเฉพาะ
String jdbcUrl = "jdbc:mysql://localhost:3306/sample?useSSL=false&serverTimezone=UTC";
String username = "root";
String password = "123456";
Connection conn = null;
try {
// 1. Load Driver (Optional ใน JDBC 4.0+ / Java 6+)
// Class.forName("com.mysql.cj.jdbc.Driver");
// 2. Establish Connection
conn = DriverManager.getConnection(jdbcUrl, username, password);
if (conn != null && !conn.isClosed()) {
System.out.println("MySQL connection successful! Port: 3306");
System.out.println("Catalog: " + conn.getCatalog());
System.out.println("Auto-commit: " + conn.getAutoCommit());
}
} catch (SQLException e) {
System.err.println("Connection failed: " + e.getMessage());
e.printStackTrace();
} finally {
// 3. Always Close Connection
if (conn != null) {
try { conn.close(); } catch (SQLException ignored) {}
}
}
}
}
Connection Properties สำคัญ
| Property | ค่าแนะนำ | คำอธิบาย |
|---|---|---|
| useSSL | false (Dev) / true (Prod) | ใช้ SSL/TLS |
| serverTimezone | UTC / Asia/Bangkok | Timezone สำหรับ DATETIME/TIMESTAMP |
| allowPublicKeyRetrieval | true | สำหรับ caching_sha2_password Auth |
| autoReconnect | true | Reconnect อัตโนมัติ (ไม่แนะนำ Production) |
| maxReconnects | 3 | จำนวนครั้ง Reconnect |
| connectTimeout | 30000 | Timeout (ms) ตอน Connect |
| socketTimeout | 30000 | Timeout (ms) ระหว่าง Query |
Best Practices
- ใช้ Connection Pool (HikariCP, DBCP2, Tomcat Pool) ไม่สร้าง Connection ใหม่ทุก Request
- Try-with-resources (Java 7+) ปิด Resource อัตโนมัติ
- PreparedStatement ป้องกัน SQL Injection
- Externalize Config: Properties File / Environment Variables / Vault
- Monitor: Connection Leaks, Pool Saturation, Query Latency
Dependency (Maven/Gradle)
<!-- Maven -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version>
</dependency>
# Gradle
implementation 'com.mysql:mysql-connector-j:8.3.0'
Troubleshooting Port 3306
- Firewall บлок Port 3306
- MySQL bind-address = 127.0.0.1 (Local Only) → เปลี่ยนเป็น 0.0.0.0
- MySQL ไม่ได้ Run / Port ผิด
- Driver Version ไม่ตรง MySQL Server Version