Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

MySQL JDBC Driver Connection String (Java)

รูปแบบ 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ค่าแนะนำคำอธิบาย
useSSLfalse / trueDev: false, Prod: true + Truststore
serverTimezoneUTC / Asia/BangkokFix "Server returns invalid timezone" Error
characterEncodingUTF-8Force UTF-8
allowPublicKeyRetrievaltrueสำหรับ caching_sha2_password (MySQL 8 Default)
rewriteBatchedStatementstrueBatch Insert เร็วขึ้นมาก
useServerPrepStmtstrueServer-side Prepared Statement
cachePrepStmtstrueCache Prepared Statements
prepStmtCacheSize250Cache Size
prepStmtCacheSqlLimit2048Max 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