How to create a database in MySQL using Python

Hello Python programmers, in this tutorial, we are going to learn how to create a database in MySQL using Python. Before jumping to the discussion on how to create MySQL database in Python, I would like to show you which Connector we are going to use and how to install it.

I am going to use MySQL Connector/Python. If you know this jump to the Python program directly.

Or you can learn How to install MySQL Connector in Python

Then I can assume that you know how to How to Connect MySQL with Python

If you don’t know don’t panic or don’t worry as the above-mentioned tutorial are so much easy that you can understand those kinds of stuff within a few minutes.

Create a database in MySQL using Python

Follow these steps:

  1. Run your MySQL Server. ( If you are using XAMPP then start Apache and MySQL from XAMPP Control panel otherwise use cmd to start MySQL server )
  2. Use the below Python Program to create a database in MySQL

Python Program to create database in MySQL

At the top of our program, we have imported mysql.connector

import mysql.connector

db_connection = mysql.connector.connect(

my_database = db_connection.cursor()

my_database.execute("CREATE DATABASE MY_TEST_DB")

If you run this program and get no errors in the output that means everything is fine.

A database with name MY_TEST_DB will be created successfully.


  • host is a variable to store the hostname. Generally, the hostname for the local server is localhost or
  • user is a variable to store the username of your MySQL server.
  • passwd is a variable to store the password of your MySQL server.

execute() function accept the MySQL statements as parameter.

To create a database in MySQL the statement is:

create database name_of_your_database

With the help of the MySQL Connector/Python we can use all acceptable MySQL statements in our Python program.

Also, learn,

How to create MySQL table in Python – Step by step tutorial

Leave a Reply
