In this example we will show how to create primary key when creating the 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 (
id INT AUTO_INCREMENT PRIMARY KEY,
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 primary key.
Output:
create primary key