Back to Python
2026-01-287 min read

MySQL Primary Key (Python Programming)

Learn MySQL Primary Key (Python Programming) step by step with clear examples and exercises.

Title: MySQL Primary Key (Python Programming)

Why This Matters

In Python programming, working with databases is essential for handling and managing large amounts of data. One crucial aspect of database management is understanding primary keys, which help ensure the integrity and uniqueness of records in a table. In this lesson, we'll delve into MySQL primary keys using Python programming, focusing on practical examples, common mistakes, and best practices.

Understanding primary keys is vital for maintaining data consistency, enforcing relationships between tables, and optimizing database performance. By learning how to create, manage, and use primary keys in your Python-MySQL projects, you'll be better equipped to build robust and efficient applications.

Prerequisites

To follow along with this lesson, you should have:

  1. Basic knowledge of Python programming
  2. Familiarity with SQL (Structured Query Language)
  3. Installation of MySQL server and Python's mysql-connector-python package
  4. A working understanding of database normalization and foreign key concepts
  5. Familiarity with creating tables, inserting data, and executing queries in MySQL
  6. Understanding the basic structure of a Python program and how to use control structures like loops and conditional statements
  7. Knowledge of handling exceptions in Python

Core Concept

A primary key is a column or set of columns in a database table that uniquely identifies each record within the table. In MySQL, you can define a primary key for a table using the PRIMARY KEY constraint. The primary key ensures data integrity by enforcing uniqueness and preventing duplicate records.

In Python, you can interact with MySQL databases using the mysql-connector-python package. To create a table with a primary key in Python, follow these steps:

  1. Import necessary modules:
import mysql.connector
from mysql.connector import Error
  1. Establish a connection to the MySQL server:
def create_connection():
try:
connection = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
return connection
except Error as e:
print(f"The error '{e}' occurred")
return None
  1. Create a cursor object to execute SQL queries:
def create_cursor(connection):
cursor = connection.cursor()
return cursor
  1. Define the table schema with a primary key:
table_schema = """
CREATE TABLE IF NOT EXISTS employees (
id INT PRIMARY KEY AUTO_INCREMENT,
firstname VARCHAR(50) NOT NULL,
lastname VARCHAR(50) NOT NULL,
email VARCHAR(100),
department_id INT,
FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE CASCADE
);
"""

In the example above, we've added a foreign key department_id that references the id column of the departments table. The ON DELETE CASCADE clause ensures that if a department is deleted, all its associated employees will also be removed.

  1. Execute the table creation query:
def create_table(cursor):
cursor.execute(table_schema)
  1. Commit the changes and close the connection:
def commit_and_close(connection, cursor):
connection.commit()
cursor.close()
connection.close()

Now that you have a table with a primary key, let's insert some records and see how MySQL enforces uniqueness and foreign key constraints.

Worked Example

To demonstrate the use of MySQL primary keys in Python, let's add some employees to our employees table:

def main():
connection = create_connection()
if connection is None:
print("Failed to connect to the database.")
return

cursor = create_cursor(connection)
if cursor is None:
print("Failed to create a cursor object.")
return

create_table(cursor)
commit_and_close(connection, cursor)

Reconnect to the database and create a new cursor

connection = create_connection()

cursor = create_cursor(connection)

Insert some employees

insert_query = """

INSERT INTO employees (firstname, lastname, email, department_id) VALUES

('John', 'Doe', 'john.doe@example.com', 1),

('Jane', 'Smith', 'jane.smith@example.com', 2),

('Mike', 'Johnson', 'mike.johnson@example.com', 3);

"""

cursor.execute(insert_query)

Insert a duplicate record (should fail)

duplicate_record = {'firstname': 'John', 'lastname': 'Doe', 'email': 'john.doe2@example.com'}

try:

insert_duplicate_query = """

INSERT INTO employees (firstname, lastname, email, department_id) VALUES

(%s, %s, %s, %s);

"""

cursor.execute(insert_duplicate_query, tuple(duplicate_record.values()))

except Error as e:

print(f"Duplicate entry error: {e}")

Insert a non-existent department ID (should fail)

invalid_dept = {'id': 4, 'name': 'Research'}

try:

insert_invalid_dept_query = """

INSERT INTO departments (id, name) VALUES

(%s, %s);

"""

cursor.execute(insert_invalid_dept_query, tuple(invalid_dept.values()))

except Error as e:

print(f"Foreign key error: {e}")

commit_and_close(connection, cursor)


When you run this code, you'll see that the duplicate record insertion and non-existent department ID insertion both fail due to the primary key and foreign key constraints. This demonstrates how MySQL enforces data integrity by preventing duplicate records in the `employees` table and maintaining referential integrity between tables.

Common Mistakes

  1. ### Forgetting to define the primary key column(s)

Remember to specify the primary key column(s) using the PRIMARY KEY constraint when creating your table schema.

  1. ### Trying to insert duplicate records without handling errors

When working with primary keys, always expect and handle potential duplicate entry errors by wrapping the insert query in a try-except block.

  1. ### Ignoring foreign key constraints

Ensure that you understand the relationships between tables and properly define foreign keys with appropriate referencing columns and cascading delete options to maintain data integrity.

  1. ### Not normalizing your database correctly

Normalize your database by separating data into multiple tables, reducing redundancy, and improving performance.

  1. ### Failing to close connections properly

Always remember to close the connection after executing queries to avoid resource leaks.

  1. ### Neglecting error handling

Handle exceptions appropriately to ensure that your program can recover gracefully from errors and continue processing data.

  1. ### Not using prepared statements for insert queries

Prepared statements help prevent SQL injection attacks by sanitizing user input before executing the query.

  1. ### Using the wrong data type for primary key columns

Choose an appropriate data type (e.g., INT, VARCHAR) for your primary key column(s), considering factors like performance and storage requirements.

  1. ### Not understanding the impact of cascading delete options

Understand the consequences of using ON DELETE CASCADE or other cascading delete options to ensure that data is deleted correctly according to your application's needs.

  1. ### Not testing your code thoroughly

Test your code with various scenarios, including inserting, updating, and deleting records, to ensure that it behaves as expected and maintains data integrity.

Practice Questions

  1. Write Python code to create a table called products with columns id, name, price, and description. Set id as the primary key.
  2. Write Python code to insert some products into the products table you created in question 1.
  3. Write Python code to update the price of a specific product (with ID 1) in the products table.
  4. Write Python code to delete a product with ID 5 from the products table.
  5. Write Python code to create a new department with ID 4 and name "Research" in the departments table.
  6. Write Python code to insert an employee named "Bob Brown" into the employees table, assigning them to the "Research" department (created in question 5).
  7. Write Python code to delete the "Research" department and all its associated employees.
  8. Write Python code to create a new table called orders with columns id, product_id, employee_id, and quantity. Set id as the primary key, and define foreign keys for product_id and employee_id.
  9. Write Python code to insert an order for product ID 1 by employee ID 2 with a quantity of 5 in the orders table.
  10. Write Python code to retrieve all orders for a specific employee (with ID 3) from the orders table.
  11. Write Python code to calculate the total cost of all orders for an employee (with ID 3).
  12. Write Python code to update the quantity of order with ID 6 to 7 in the orders table.
  13. Write Python code to delete the order with ID 6 from the orders table.

FAQ

Q: Can I have multiple columns as part of a primary key?

A: Yes, you can define composite primary keys by separating the column names with a comma in the PRIMARY KEY constraint. For example, PRIMARY KEY (column1, column2).

Q: What happens if I try to delete a record that has a foreign key referencing it?

A: When you attempt to delete a record with a foreign key dependency, MySQL will prevent the deletion and return an error. You can use the ON DELETE CASCADE clause in your foreign key definition to automatically delete dependent records when the parent record is deleted.

Q: How do I handle situations where a foreign key refers to multiple records in the referenced table?

A: In such cases, you should define the foreign key as INT NOT NULL, and use subqueries or joins to select the appropriate records from the referenced table.

Q: Can I change the primary key of an existing table?

A: Changing a primary key is complex and generally not recommended. However, if necessary, you can create a new table with the desired schema, populate it with data from the old table, drop the old table, and rename the new table to the original name.

Q: How do I optimize my database for performance?

A: To optimize your database for performance, consider indexing frequently queried columns, using prepared statements, minimizing data redundancy through normalization, and tuning MySQL configuration settings like innodb_buffer_pool_size.

Q: What are some best practices for writing efficient SQL queries?

A: Some best practices for writing efficient SQL queries include using indexes appropriately, avoiding unnecessary subqueries, minimizing the use of SELECT \* statements, and optimizing JOIN operations by ordering your tables correctly.

Q: How can I secure my MySQL database against unauthorized access?

A: To secure your MySQL database, use strong passwords for users, limit user privileges to only what is necessary, enable authentication plugins like mysql_native_password or caching_sha2_password, and configure firewall rules to restrict access to the MySQL server.

MySQL Primary Key (Python Programming) | Python | XQA Learn