In order to create a MySQL database in Python, you first need to initiate a connection using the mysql.connector
. You can learn about how to create a connection to MySQL here
.
How to Create a Database in Python
Creating a database is simple.
First, make sure you have an active connection to your database, and then set a cursor
.
Once you have this, issue the execute
command to create your database.
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "username",
password = "YoUrPaSsWoRd"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE your_database")
How to Check if a MySQL Database Exists in Python
Using a similar connection as described above, execute
the SHOW DATABASES
query.
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "username",
password = "YoUrPaSsWoRd"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
How to Connect to a MySQL Database in Python
Now that you know which database to connect to, you can specify it directly in the beginning.
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "username",
password = "YoUrPaSsWoRd",
database="your_database"
)