Python MySQL – Create Table

To create a table in MySQL from Python, we run the SQL CREATE TABLE command with the cursor. Before this, you should know how to connect Python to MySQL.


Create the users table

We create a table named users in the student database with four columns.

ColumnTypeMeaning
idINT AUTO_INCREMENT PRIMARY KEYUnique number, MySQL fills it automatically
nameVARCHAR(100)Name of the user, required
mobileVARCHAR(15)Mobile number as text
emailVARCHAR(100)Email address
import mysql.connector

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="student"
)
cursor = conn.cursor()

cursor.execute("""
    CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        mobile VARCHAR(15),
        email VARCHAR(100)
    )
""")

print("Table users is ready")

cursor.close()
conn.close()
Output of the above program is

Table users is ready

We used IF NOT EXISTS, so running the program again does not give an error if the table is already there. Without it MySQL raises an error that the table exists.


Check that the table exists

Use the SHOW TABLES command and loop over the cursor.

import mysql.connector

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="student"
)
cursor = conn.cursor()

cursor.execute("SHOW TABLES")

for table in cursor:
    print(table)

cursor.close()
conn.close()
Output of the above program is

('users',)

Note: Each row from the cursor comes as a tuple. That is why the table name is shown in brackets with a comma.

Summary

  • Run CREATE TABLE with cursor.execute().
  • Use IF NOT EXISTS to make the program safe to run again.
  • Use SHOW TABLES to check your tables.
  • Next: insert data into the table.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.