Introduction

MySQL is one of the most popular relational database management systems used to store, manage and retrieve data efficiently. In this tutorial, we will explore how we can leverage the power of Python to create and manipulate MySQL databases. By the end of this tutorial, you will have the skills and knowledge to create a MySQL database using Python programming language. So, let’s get started!

Table of Contents :

  • How to create database in MySQL with Python
    • Step 1: Install the required Packages
    • Step 2: Establishing a Connection to the MySQL Server
    • Step 3: Create a Cursor Object
    • Step 4: Create a MySQL Database

How to create database in MySQL with Python :

  • Follow the steps given below to create database in MySQL with python 
    • Step 1: Install the required Packages
    • Step 2: Establishing a Connection to the MySQL Server
    • Step 3: Create a Cursor Object
    • Step 4: Create a MySQL Database

Step 1: Install the Required Packages

  • The first step is to ensure that you have installed the required packages on your machine.
  • The most popular packages for connecting to MySQL in Python are 
    • mysql-connector and 
    • PyMySQL.
  • You can install these packages using pip through the command line.
  • Example:

!pip install mysql-connector-python
!pip install PyMySQL

Step 2: Connect to the MySQL Database

  • To create a new database in MySQL using Python, we must have a connection to the MySQL server.
  • To connect to a MySQL server in Python we can use either 
    • mysql.connector or 
    • PyMySQL package 
  • We need to provide the necessary connection parameters to establish the connection.
  • We need to pass the following parameters to the Connection object: 
    • host : the hostname  of the MySQL server user 
    • user : username for the MySQL account
    • password : password for the MySQL account database
    • database : Db name to connect to 
  • To study package specific code for connecting to MySQL read our tutorial on connecting to MySQL server.

Step 3: Create a Cursor Object

  • After establishing a connection to the MySQL server, your next step is to create a cursor object.
  • This is done using the cursor() method provided by mysql.connector or PyMySQL.
  • Example:

cursor = mydb.cursor()

Step 4: Create a MySQL Database

  • With a cursor object, you can now create a new database on the MySQL server.
  • This is done using SQL query CREATE DATABASE.
  • Example:


# Create Database using cursor object
cursor.execute("CREATE DATABASE mydatabase")

Prev. Tutorial : Connect to mysql