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

เลือกใช้งาน JDBC Driver 4 ประเภท ใช้ตัวไหนเมื่อไหร่

JDBC Driver แบ่งได้ 4 ประเภท (Type 1-4) เลือกใช้ตามสถานการณ์ดังนี้:

Type 1: JDBC-ODBC Bridge Driver

  • ลักษณะ: แปลง JDBC → ODBC → Database
  • ใช้เมื่อ: พัฒนา/ทดสอบ (Development/Testing) เท่านั้น
  • ข้อเสีย: ต้องติดตั้ง ODBC Driver บน Client, ช้า, ไม่รองรับการกระจาย (Deployment)
  • สถานะ: Deprecated ตั้งแต่ Java 8, ลบออกใน Java 11

Type 2: Native-API Driver

  • ลักษณะ: แปลง JDBC → Native API ของ Database (Client Library)
  • ใช้เมื่อ: ไม่มี Type 3 หรือ 4 สำหรับ Database นั้นๆ
  • ข้อเสีย: ต้องติดตั้ง Library บน Client, Platform-dependent
  • ตัวอย่าง: Oracle OCI Driver

Type 3: Network Protocol Driver (Middleware)

  • ลักษณะ: JDBC → Middleware Server → Database (3-tier)
  • ใช้เมื่อ: แอปพลิเคชันเข้าถึง หลายประเภท Database พร้อมกัน
  • ข้อดี: Client ไม่ต้องติดตั้ง Library, รองรับหลาย Database
  • ข้อเสีย: ต้องมี Middleware Server, เพิ่มความซับซ้อน
  • ตัวอย่าง: DataDirect SequeLink

Type 4: Thin Driver (Pure Java) - แนะนำมากที่สุด

  • ลักษณะ: Pure Java, ต่อ Database โดยตรงผ่าน Network Protocol
  • ใช้เมื่อ: เข้าถึง Database ประเภทเดียว (Oracle, MySQL, PostgreSQL, SQL Server, etc.)
  • ข้อดี: ไม่ต้องติดตั้งอะไรบน Client, Cross-platform, ประสิทธิภาพดีที่สุด
  • ตัวอย่าง: MySQL Connector/J, PostgreSQL JDBC, Oracle Thin Driver, Microsoft JDBC Driver for SQL Server

ตารางสรุปการเลือก

MySQL Connector/J (Type 4) - ตัวอย่างการใช้งาน

// Maven Dependency

    com.mysql
    mysql-connector-j
    8.0.33


// Connection
String url = "jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC";
Connection conn = DriverManager.getConnection(url, "user", "password");
สถานการณ์Driver Type ที่แนะนำ
Production: เข้าถึง Database เดียว (MySQL, PostgreSQL, Oracle, SQL Server)Type 4
Production: เข้าถึงหลาย Database พร้อมกันType 3
Database เก่าที่ไม่มี Type 4 DriverType 2
Development/Testing เท่านั้นType 1 (ไม่แนะนำ)