How to Create a Primary Key for a MySQL Database in Python

You can create a Primary Key for your MySQL database in Python as follows.

First, you need to know if the Primary Key already exists.

Option 1 – The Primary Key does not Exist

import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
Code language: Python (python)

Option 2 – The Primary Key already Exists

import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database = "your_database" ) mycursor = mydb.cursor() mycursor.execute("ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")
Code language: Python (python)

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments