Python MySQL - Create Database

Last Updated : 3 Jun, 2026

In Python, a MySQL database can be created using the CREATE DATABASE statement. The mysql.connector module is used to connect Python programs with the MySQL server and execute database creation queries.

Syntax

CREATE DATABASE database_name;

Examples

Example 1: In this example, the code connects to the MySQL server and creates a database named company.

Python
import mysql.connector

dataBase = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="1234"
)

cursorObject = dataBase.cursor()

cursorObject.execute("CREATE DATABASE company")
print("Database created successfully.")

Output

Database created successfully.

Explanation:

  • mysql.connector.connect() connects Python with the MySQL server.
  • cursor() creates a cursor object used to execute SQL queries.
  • CREATE DATABASE company creates a database named company.
  • print() displays the success message after database creation.

Example 2: Here, the code creates a database named school only if it does not already exist in the MySQL server.

Python
import mysql.connector

dataBase = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="1234"
)

cursorObject = dataBase.cursor()
cursorObject.execute("CREATE DATABASE IF NOT EXISTS school")
print("Database checked/created successfully.")
dataBase.close()

Output

Database checked/created successfully.

Explanation:

  • CREATE DATABASE IF NOT EXISTS school creates the database only if it is not already present.
  • This prevents errors caused by trying to create an existing database.
  • close() closes the connection with the MySQL server after execution.
Comment