Python MySQL Tạo cơ sở dữ liệu
Tạo cơ sở dữ liệu
Để tạo cơ sở dữ liệu trong MySQL, hãy sử dụng câu lệnh "TẠO CƠ SỞ DỮ LIỆU":
Thí dụ
tạo cơ sở dữ liệu có tên "mydatabase":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE
mydatabase")
Nếu đoạn mã trên được thực thi mà không có lỗi, bạn đã tạo thành công cơ sở dữ liệu.
Kiểm tra xem cơ sở dữ liệu có tồn tại không
Bạn có thể kiểm tra xem cơ sở dữ liệu có tồn tại hay không bằng cách liệt kê tất cả cơ sở dữ liệu trong hệ thống của mình bằng cách sử dụng câu lệnh "HIỂN THỊ DỮ LIỆU":
Thí dụ
Trả lại danh sách cơ sở dữ liệu hệ thống của bạn:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
Hoặc bạn có thể cố gắng truy cập cơ sở dữ liệu khi thực hiện kết nối:
Thí dụ
Thử kết nối với cơ sở dữ liệu "mydatabase":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
Nếu cơ sở dữ liệu không tồn tại, bạn sẽ gặp lỗi.