โค้ด Java สำหรับเชื่อมต่อ MySQL
import java.sql.Connection;
import java.sql.DriverManager;
public class LostConnectionURLDemo {
public static void main(String[] args) {
String JDBC_URL = "jdbc:mysql://localhost:3306/web?autoReconnect=true";
Connection con = null;
try {
con = DriverManager.getConnection(JDBC_URL, "root", "123456");
System.out.println("connection is established");
} catch (Exception e) {
e.printStackTrace();
}
}
}
องค์ประกอบของ JDBC URL
| ส่วน | คำอธิบาย |
|---|---|
jdbc:mysql:// | Protocol และ Driver |
localhost:3306 | Host และ Port (3306 = default MySQL) |
/web | Database Name |
?autoReconnect=true | Parameter: reconnect อัตโนมัติหากขาดการเชื่อมต่อ |