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

แก้ไขข้อผิดพลาดการเชื่อมต่อ Java MySQL ต้องตั้ง Classpath ให้ Connector

แก้ไขข้อผิดพลาดการเชื่อมต่อโดยเพิ่ม MySQL Connector ใน Classpath

ต้องนำไฟล์ JAR ของ MySQL Connector/J ไปวางในโฟลเดอร์โปรเจกต์ หรือเพิ่มใน Build Path ของ IDE

ขั้นตอนการตั้งค่า

  1. ดาวน์โหลด MySQL Connector/J (mysql-connector-java-x.x.x.jar)
  2. ใน IDE (Eclipse/IntelliJ/NetBeans) เพิ่ม JAR เข้า Build Path / Libraries
  3. หรือวางไฟล์ JAR ในโฟลเดอร์ lib ของโปรเจกต์

โค้ดเชื่อมต่อตัวอย่าง

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

public class MySQLConnection {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/web?useSSL=false";
        try (Connection con = DriverManager.getConnection(url, "root", "123456")) {
            System.out.println("Connected successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

ข้อผิดพลาดทั่วไป: ClassNotFoundException: com.mysql.jdbc.Driver → ไม่มี Connector ใน Classpath | Communications link failure → IP/Port ผิด หรือ Firewall บล็อก