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 "CREATE DATABASE":
Ví 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")
Chạy ví dụ »Nếu đoạn mã trên được thực thi không có lỗi thì bạn đã tạo cơ sở dữ liệu thành công.
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âu lệnh "SHOW DATABASES":
Ví dụ
Trả về danh sách cơ sở dữ liệu của 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)
Chạy ví dụ »Hoặc bạn có thể thử truy cập cơ sở dữ liệu khi thực hiện kết nối:
Ví dụ
Hãy 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"
)
Chạy ví dụ »Nếu cơ sở dữ liệu không tồn tại, bạn sẽ gặp lỗi.