Methods to Create a Main Key for a MySQL Database in Python


You’ll be able to create a Main Key to your MySQL database in Python as follows.

First, it’s worthwhile to know if the Main Key already exists.

Possibility 1 – The Main Key doesn’t Exist

import mysql.connector

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

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE clients (id INT AUTO_INCREMENT PRIMARY KEY, identify VARCHAR(255), deal with VARCHAR(255))")

Possibility 2 – The Main Key already Exists

import mysql.connector

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

mycursor = mydb.cursor()

mycursor.execute("ALTER TABLE clients ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")

Leave a Reply