Python MySQL Create Database (original) (raw)

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:

**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: