How to Create Primary Key On an Existing Table in Python


In this example we will show how to create primary key on an existing 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()

sql = """ALTER TABLE US_STATE ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY"""

# execute a query
mycursor.execute(sql)

# close the connection
mydb.close()

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