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

สร้างฐานข้อมูล MySQL จาก Java (JDBC)

ใช้ Statement.executeUpdate() รันคำสั่ง CREATE DATABASE

โค้ด Java สมบูรณ์

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

public class CreateDatabaseDemo {
    public static void main(String[] args) {
        Connection con = null;
        Statement stmt = null;
        String yourDatabaseName = "Customer_Tracker_Database";
        try {
            con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/test3?useSSL=false",
                "root", "123456");
            stmt = con.createStatement();
            int status = stmt.executeUpdate("CREATE DATABASE " + yourDatabaseName);
            if (status > 0) {
                System.out.println("Database is created successfully !!!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

ผลลัพธ์

Database is created successfully !!!

ตรวจสอบใน MySQL

mysql> SHOW DATABASES;

ผลลัพธ์ (เห็น Customer_Tracker_Database):

+------------------------------+
| Database                     |
+------------------------------+
| ...                          |
| Customer_Tracker_Database    |
| ...                          |
+------------------------------+

คำอธิบายโค้ด

  • เชื่อมต่อไปที่ database ใดก็ได้ที่มีอยู่ (ที่นี่คือ test3) เพื่อสร้าง database ใหม่
  • executeUpdate() ใช้สำหรับ DDL (CREATE, ALTER, DROP) และ DML (INSERT, UPDATE, DELETE)
  • คืนค่า int: จำนวนแถวที่ได้รับผลกระทบ (สำหรับ DDL มักคืน 0 หรือ 1)
  • ไม่ต้องใช้ ResultSet เพราะไม่มีข้อมูลคืนมา

แนวทางปฏิบัติที่ดีกว่า (Best Practices)

// ใช้ try-with-resources ปิดทรัพยากรอัตโนมัติ (Java 7+)
try (Connection con = DriverManager.getConnection(url, user, pass);
     Statement stmt = con.createStatement()) {
    
    String dbName = "Customer_Tracker_Database";
    // ใช้ backticks ป้องกันชื่อมีอักขระพิเศษ
    stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS `" + dbName + "`");
    System.out.println("Database created or already exists");
} catch (SQLException e) {
    e.printStackTrace();
}

สิทธิ์ที่ต้องการ

ผู้ใช้ต้องมีสิทธิ์ CREATE บนระดับ global (*.*)