Python Create Database

Create Database

To create a database in MySQL, please use the "CREATE DATABASE" statement:

Example

Create a database named "mydatabase":

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")

Run Example

If there are no errors when executing the above code, then you have successfully created the database.

Check if the database exists

You can list all the databases in the system using the "SHOW DATABASES" statement and check if the database exists:

Example

Return the list of databases in the system:

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)

Run Example

Or you can try to access the database when establishing the connection:

Example

Attempt to connect to the database "mydatabase":

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
)

Run Example

An error will be received if the database does not exist.