Back to C++
2026-03-026 min read

MySQL Primary Key (C++)

Learn MySQL Primary Key (C++) step by step with clear examples and exercises.

Title: MySQL Primary Key (C++)

Why This Matters

In this lesson, we will delve into the creation and management of primary keys in MySQL databases using C++. Understanding primary keys is essential for efficient data management, ensuring data integrity, and optimizing database performance during query operations. This knowledge will be valuable for developers working on projects that involve complex databases, particularly in web development or data-intensive applications.

Primary keys are crucial components of a well-designed database as they ensure the uniqueness of each record and enable efficient querying. By learning how to work with primary keys in C++, you will be able to create robust and scalable applications that interact seamlessly with MySQL databases.

Prerequisites

To follow this lesson, you should have a basic understanding of the following:

  • C++ programming language syntax and concepts (variables, functions, loops, etc.)
  • MySQL database management system and SQL queries
  • How to compile and run C++ programs using a compiler like g++
  • Familiarity with STL containers such as std::vector and std::map
  • Basic understanding of exception handling in C++
  • Knowledge of how to establish a connection between C++ and MySQL using the mysql library

Core Concept

A primary key is a unique column or set of columns in a database table that identifies each row unambiguously. In MySQL, primary keys are used to enforce data integrity by ensuring that no duplicate rows can be inserted into the table. Primary keys also provide a performance boost when querying specific records due to their efficient indexing mechanism.

In C++, we use the mysql library to interact with MySQL databases. To create a table with a primary key, we first need to establish a connection to the database and then execute SQL queries to create the table structure.

Here's an example of creating a simple table called employees with an id column as the primary key:

#include <iostream>
#include <mysql/mysql.h>
#include <vector>
#include <stdexcept>

void connectDB(MYSQL **conn) {
*conn = mysql_init(nullptr);
if (*conn == nullptr) {
throw std::runtime_error("Failed to initialize MySQL connection");
}

if (mysql_real_connect(*conn, "localhost", "<username>", "<password>", "<database>", 0, NULL, 0) == nullptr) {
throw std::runtime_error("Failed to connect to the database");
}
}

void createTable(MYSQL *conn) {
mysql_query(*conn, "CREATE TABLE IF NOT EXISTS employees ("
"id INT PRIMARY KEY AUTO_INCREMENT,"
"name VARCHAR(255),"
"age INT,"
"position VARCHAR(255)"
");");
}

Creating Records and Querying Data

After creating the table, we can insert records into it using SQL queries:

void insertEmployee(MYSQL *conn, const std::string &name, int age, const std::string &position) {
mysql_query(*conn, "INSERT INTO employees (name, age, position) VALUES ('" + name + "', " + std::to_string(age) + ", '" + position + "');");
}

void printAllEmployees(MYSQL *conn) {
MYSQL_RES *result = mysql_store_result(conn);
MYSQL_ROW row;

while ((row = mysql_fetch_row(result))) {
std::cout << row[0] << ", " << row[1] << ", " << row[2] << ", " << row[3] << "\n";
}
}

Updating and Deleting Records

We can also update and delete records using SQL queries:

void updateEmployee(MYSQL *conn, int id, const std::string &name, int age, const std::string &position) {
mysql_query(*conn, "UPDATE employees SET name='" + name + "', age=" + std::to_string(age) + ", position='" + position + "' WHERE id=" + std::to_string(id) + ";");
}

void deleteEmployee(MYSQL *conn, int id) {
mysql_query(*conn, "DELETE FROM employees WHERE id=" + std::to_string(id) + ";");
}

Worked Example

Let's create a simple example where we insert, retrieve, update, and delete records from the employees table using C++.

  1. First, compile the code above to create an executable named create_table.cpp.
g++ -o create_table create_table.cpp -lmysqlclient
  1. Run the compiled program to create the employees table in the database and insert some sample data:
./create_table
  1. Now, let's write another C++ program to interact with the employees table. Create a new file called interact_with_employees.cpp.
#include <iostream>
#include <mysql/mysql.h>
#include <vector>
#include <stdexcept>

void connectDB(MYSQL **conn) {
*conn = mysql_init(nullptr);
if (*conn == nullptr) {
throw std::runtime_error("Failed to initialize MySQL connection");
}

if (mysql_real_connect(*conn, "localhost", "<username>", "<password>", "<database>", 0, NULL, 0) == nullptr) {
throw std::runtime_error("Failed to connect to the database");
}
}

void createTable(MYSQL *conn) {
mysql_query(*conn, "CREATE TABLE IF NOT EXISTS employees ("
"id INT PRIMARY KEY AUTO_INCREMENT,"
"name VARCHAR(255),"
"age INT,"
"position VARCHAR(255)"
");");
}

void insertEmployee(MYSQL *conn, const std::string &name, int age, const std::string &position) {
mysql_query(*conn, "INSERT INTO employees (name, age, position) VALUES ('" + name + "', " + std::to_string(age) + ", '" + position + "');");
}

void printAllEmployees(MYSQL *conn) {
MYSQL_RES *result = mysql_store_result(conn);
MYSQL_ROW row;

while ((row = mysql_fetch_row(result))) {
std::cout << row[0] << ", " << row[1] << ", " << row[2] << ", " << row[3] << "\n";
}
}

void updateEmployee(MYSQL *conn, int id, const std::string &name, int age, const std::string &position) {
mysql_query(*conn, "UPDATE employees SET name='" + name + "', age=" + std::to_string(age) + ", position='" + position + "' WHERE id=" + std::to_string(id) + ";");
}

void deleteEmployee(MYSQL *conn, int id) {
mysql_query(*conn, "DELETE FROM employees WHERE id=" + std::to_string(id) + ";");
}

int main() {
MYSQL *conn;
connectDB(&conn);

createTable(conn);

// Insert a new employee record
insertEmployee(conn, "John Doe", 30, "Software Engineer");
std::cout << "Inserted John Doe\n";

// Print all records from the employees table
printAllEmployees(conn);

// Update John Doe's age to 31
updateEmployee(conn, 1, "John Doe", 31, "Senior Software Engineer");
std::cout << "Updated John Doe's age\n";

// Print updated records from the employees table
printAllEmployees(conn);

// Delete John Doe from the employees table
deleteEmployee(conn, 1);
std::cout << "Deleted John Doe\n";

// Print remaining records from the employees table (should be empty)
printAllEmployees(conn);

mysql_close(conn);

return 0;
}
  1. Compile and run the new program to interact with the employees table:
g++ -o interact_with_employees interact_with_employees.cpp -lmysqlclient
./interact_with_employees

Common Mistakes

  1. Forgetting to set the primary key column: Remember to include PRIMARY KEY in the table creation statement for the primary key column.
  2. Inserting duplicate records: MySQL will not allow inserting duplicate primary keys into a table. Ensure that each record you insert has a unique primary key value.
  3. Not specifying the primary key column in WHERE clauses: When updating or deleting records, always use the primary key column in the WHERE clause to ensure accurate results.
  4. Not handling connection errors properly: Always check for connection errors and handle them appropriately to prevent program crashes.
  5. Using text or large integer values as primary keys: These can negatively impact query performance due to their larger size compared to integers.
  6. Creating tables without a primary key: This can lead to data integrity issues, as there will be no unique identifier for each row in the table.
  7. Not normalizing data properly: Poorly designed tables with redundant data can negatively impact database performance and overall design.

Practice Questions

  1. Create a new table called products with columns id, name, price, and quantity. Set the id column as the primary key.
  2. Write a C++ program to insert, retrieve, update, and delete records from the products table using the provided functions (insertEmployee, printEmployees, updateEmployee, deleteEmployee).
  3. Implement a function that checks if a given product ID exists in the products table.
  4. Modify the previous example to handle connection errors more gracefully by displaying an error message and exiting the program when a connection cannot be established.
  5. Create a function that retrieves all products with a price greater than a specified value.
  6. Normalize the employees table by creating separate tables for departments and positions, then update the employees table to reference these new tables.

FAQ

  1. Can I change the primary key of a table after it has been created?
  • No, you cannot change the primary key of a table once it has been created. You should carefully design your tables to ensure that the chosen primary keys are unique and suitable for your data needs.
  1. What happens if I try to insert a duplicate primary key into a table?
  • MySQL will not allow you to insert a duplicate primary key into a table. If an attempt is made, it will return an error indicating that the violation of the primary key constraint has occurred.
  1. Can I have multiple primary keys in a table?
  • Yes, you can create a composite primary key by specifying multiple columns as the primary key. However, this is not commonly used and may impact query performance due to the increased complexity of the indexing mechanism.
  1. What are some best practices for designing tables with primary keys in MySQL?
  • Choose primary keys that are unique, small, and immutable. Avoid using text or large integer values as primary keys, as they can negatively impact query performance. Additionally, consider normalizing your data to minimize redundancy and improve overall database design.
MySQL Primary Key (C++) | C++ | XQA Learn