Python tạo cơ sở dữ liệu
- Trang Trước MySQL Bắt Đầu
- Trang Tiếp Theo MySQL Tạo Bảng
Tạo cơ sở dữ liệu
Nếu bạn muốn tạo cơ sở dữ liệu trong MySQL, hãy sử dụng câu lệnh "CREATE DATABASE":
Mô Hình
Tạo cơ sở dữ liệu có tên "mydatabase":
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword" ) mycursor = mydb.cursor() mycursor.execute("CREATE DATABASE mydatabase")
Nếu không có lỗi khi thực hiện mã trên, bạn đã thành công trong việc tạo cơ sở dữ liệu.
Kiểm tra cơ sở dữ liệu có tồn tại hay không
Bạn có thể sử dụng câu lệnh "SHOW DATABASES" để liệt kê tất cả các cơ sở dữ liệu trong hệ thống, kiểm tra cơ sở dữ liệu có tồn tại hay không:
Mô Hình
Trả về danh sách cơ sở dữ liệu trong hệ thống:
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword" ) mycursor = mydb.cursor() mycursor.execute("SHOW DATABASES") for x in mycursor: print(x)
hoặc bạn có thể thử truy cập cơ sở dữ liệu khi thiết lập kết nối:
Mô Hình
Thử kết nối cơ sở dữ liệu "mydatabase":
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" )
Nếu cơ sở dữ liệu không tồn tại, bạn sẽ nhận được lỗi.
- Trang Trước MySQL Bắt Đầu
- Trang Tiếp Theo MySQL Tạo Bảng