Python MySQL Create Table Explained with Examples

In order to create a table in MySQL using Python script, you can execute a CREATE TABLE query through the cursor.execute() method.

Syntax

cursor.execute("CREATE TABLE table_name (column1 datatype, column2 datatype, ...)")

Example

import mysql.connector

# Establish connection to MySQL server
connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="password",
    database="mydatabase"
)

cursor = connection.cursor()

# Execute a CREATE TABLE query
create_table_query = """
CREATE TABLE employees (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50),
    department VARCHAR(50),
    salary DECIMAL(10, 2)
)
"""
cursor.execute(create_table_query)

connection.close()