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

0 min read 106 words

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))")

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")
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts