How to Create a MySQL Table in Python


In this example we will show how to create a MySQL table in Python.

Source Code

import mysql.connector

# connect to server
mydb = mysql.connector.connect(
    host="localhost",
    port=3306,
    user="yourusername",
    password="yourpassword",
    db="mydatabase"
)

# get a cursor
mycursor = mydb.cursor()

# delete if the table exists
mycursor.execute("DROP TABLE IF EXISTS US_STATE")

sql = """CREATE TABLE US_STATE (
         State_name CHAR(30),
         Abbreviation  CHAR(10),
         Capital  CHAR(30),
         Total_area INT)"""

# execute a query
mycursor.execute(sql)

# close the connection
mydb.close()

# If the above code is executed with no error, you have successfully created a table.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments