รูปแบบ Connection String สำหรับ MySQL Connector/J (JDBC Driver)
Driver Class
Class.forName("com.mysql.cj.jdbc.Driver"); // MySQL 8.0+ (cj package)
-- เดิม: com.mysql.jdbc.Driver (5.1.x, Deprecated)
Connection URL Format
jdbc:mysql://[host][:port]/[database]?[property1=value1&property2=value2...]
ตัวอย่างโค้ด Java
String url = "jdbc:mysql://localhost:3306/yourDatabase?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8"; String user = "yourUsername"; String password = "yourPassword"; Connection conn = DriverManager.getConnection(url, user, password);
Properties สำคัญ
| Property | ค่าแนะนำ | คำอธิบาย |
|---|---|---|
useSSL | false / true | Dev: false, Prod: true + Truststore |
serverTimezone | UTC / Asia/Bangkok | Fix "Server returns invalid timezone" Error |
characterEncoding | UTF-8 | Force UTF-8 |
allowPublicKeyRetrieval | true | สำหรับ caching_sha2_password (MySQL 8 Default) |
rewriteBatchedStatements | true | Batch Insert เร็วขึ้นมาก |
useServerPrepStmts | true | Server-side Prepared Statement |
cachePrepStmts | true | Cache Prepared Statements |
prepStmtCacheSize | 250 | Cache Size |
prepStmtCacheSqlLimit | 2048 | Max SQL Length to Cache |
Connection Pool (HikariCP - แนะนำ)
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/db?useSSL=false&serverTimezone=UTC");
config.setUsername("user");
config.setPassword("pass");
config.setMaximumPoolSize(20);
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
DataSource ds = new HikariDataSource(config);
หมายเหตุ: MySQL 8.0+ ใช้caching_sha2_passwordเป็น Default Authentication ต้องเพิ่มallowPublicKeyRetrieval=trueหรือใช้mysql_native_passwordสำหรับ User