Create Table in Python MySQL

Python MySQL – Create Table

To create a table in Python MySQL,

  1. Create a connection to the MySQL database with user credentials and database name, using connect() function.
  2. Get the cursor to the database using cursor() function.
  3. Take a CREATE TABLE statement and execute it using execute() function.


Consider that we have a schema named mydatabase in MySQL. We have access to the database with credentials: user – root and password – admin1234.

In the following program, we create a table named fruits, with columns: name, quantity, and country, where name is the PRIMARY KEY.

Python Program

import mysql.connector

mydb = mysql.connector.connect(

mycursor = mydb.cursor()

sql = "CREATE TABLE fruits (name VARCHAR(50) NOT NULL, quantity INT DEFAULT 0, country VARCHAR(50), PRIMARY KEY (name))"
print('Table created successfully.')


Database before table creation

Database after table creation


In this tutorial of Python Examples, we learned how to create a table in MySQL database.

⫷ Previous tutorialNext tutorial ⫸