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.