Mã Java hoàn chỉnh
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) { -- executeUpdate trả về 0 cho DDL
System.out.println("Database is created successfully !!!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Đóng tài nguyên
try { if (stmt != null) stmt.close(); } catch (Exception e) {}
try { if (con != null) con.close(); } catch (Exception e) {}
}
}
}
Giải thích
executeUpdate(): Dùng cho DDL (CREATE, ALTER, DROP) và DML (INSERT, UPDATE, DELETE)
- Trả về: Số dòng ảnh hưởng (DML) hoặc 0 (DDL)
- Kết nối đến database hiện có (
test3) để tạo database mới
- Tên database:
Customer_Tracker_Database
Kiểm tra database đã tạo
mysql> SHOW DATABASES;
+------------------------------+
| Database |
+------------------------------+
| Customer_Tracker_Database |
| ... (các database khác) |
+------------------------------+
Best Practices
- Dùng
try-with-resources (Java 7+) để tự đóng Connection/Statement
- Escape tên database:
` + name + ` nếu chứa ký tự đặc biệt
- Kiểm tra tồn tại:
CREATE DATABASE IF NOT EXISTS ten_db
- Charset/collation:
CREATE DATABASE ten_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
- Connection pool (HikariCP) cho ứng dụng production
Với try-with-resources (Java 7+)
try (Connection con = DriverManager.getConnection(url, user, pass);
Statement stmt = con.createStatement()) {
stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS " + dbName);
System.out.println("Database created!");
}