The right way to Create a Main Key for a MySQL Database in Python


You may create a Main Key on your MySQL database in Python as follows.

First, you have to know if the Main Key already exists.

Choice 1 – The Main Key doesn’t Exist

import mysql.connector

mydb = mysql.connector.join(
  host = "localhost",
  person = "username",
  password = "YoUrPaSsWoRd",
  database = "your_database"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE prospects (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255), tackle VARCHAR(255))")

Choice 2 – The Main Key already Exists

import mysql.connector

mydb = mysql.connector.join(
  host = "localhost",
  person = "username",
  password = "YoUrPaSsWoRd",
  database = "your_database"
)

mycursor = mydb.cursor()

mycursor.execute("ALTER TABLE prospects ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")
See also  Enjoying the Alphabet Warfare in Python

Leave a Reply