C Database MySQL Select Statement

MySQL Connection In C

The C MySQL Connector is required for C to connect to the database.

A separate MariaDB C Connector is available and can be installed.

The MySQL header must be included first. This tutorial uses MariaDB 10.11.8 and GCC 14.2.1 on Fedora Linux 40.

MySQL Interface

Sample MySQL functions
Name Description Example
mysql_real_connect Create database connection mysql_real_connect(conn, hostname, dbuser, dbpass, dbname)
execute Perform database query execute(query)
mysql_num_rows Gets the number of rows in the result set mysql_num_rows(MYSQL_RES *result)
Name Description Example

Install MySQL Driver

dnf install mariadb-connector-c-devel

C MySQL Select Data

#include <stdio.h>                                                                                   
#include <stdlib.h>                                                                                  
#include <mysql/mysql.h>                                                                             

int main(void)                                                                                       
{                                                                                                    
	MYSQL *conn;                                                                                       

	if ((conn = mysql_init(NULL)) == NULL)                                                             
	{                                                                                                  
		fprintf(stderr, "Could not init DB\n");                                                 
		return EXIT_FAILURE;                                                                             
	}                                                                                                  
	if (mysql_real_connect(conn, "localhost", "dbuser", "dbpass", "dbname", 0, NULL, 0) == NULL)             
	{                                                                                                  
		fprintf(stderr, "DB Connection Error\n");                                                        
		return EXIT_FAILURE;                                                                             
	}                                                                                                  
	if (mysql_query(conn, "SELECT sid, name, age FROM Students") != 0)                   
	{                                                                                                  
		fprintf(stderr, "Query Failure\n");                                                              
		return EXIT_FAILURE;                                                                             
	}

	MYSQL_RES *result = mysql_store_result(conn);
	int num_fields = mysql_num_fields(result);
	MYSQL_ROW row;
	while ((row = mysql_fetch_row(result)))
	{
		for(int i = 0; i < num_fields; i++)
		{
			 printf("%s ", row[i] ? row[i] : "NULL");
		}

		printf("\n");
	}
		
	mysql_free_result(result);                                                                           
	mysql_close(conn);                                                                                 
	return EXIT_SUCCESS;                                                                               
}

SQL Injection Security Warning

Variable input must be sanitized, validated, properly formatted and escaped. For this tutorial, the variable input is known and trusted and security is not concerning.

C MySQL Select Data Escape String

#include <stdio.h>                                                                                   
#include <stdlib.h>                                                                            
#include <string.h>                                                                            
#include <mysql/mysql.h>                                                                             

int main(void)                                                                                       
{                                                                                                    
	MYSQL *conn;                                                                                       

	if ((conn = mysql_init(NULL)) == NULL)                                                             
	{                                                                                                  
		fprintf(stderr, "Could not init DB\n");                                                 
		return EXIT_FAILURE;                                                                             
	}                                                                                                  
	if (mysql_real_connect(conn, "localhost", "dbuser", "dbpass", "dbname", 0, NULL, 0) == NULL)             
	{                                                                                                  
		fprintf(stderr, "DB Connection Error\n");                                                        
		return EXIT_FAILURE;                                                                             
	}
	char from[100];
	char to[100];
	char query[1000];
	sprintf(from, "D'Arcy");
	mysql_escape_string(to, from, strlen(from));
	sprintf(query, "SELECT sid, name, age FROM Students WHERE name = '%s'", to);
	if (mysql_query(conn, query) != 0)                   
	{                                                                                                  
		fprintf(stderr, "Query Failure\n");                                                              
		return EXIT_FAILURE;                                                                             
	}

	MYSQL_RES *result = mysql_store_result(conn);
	int num_fields = mysql_num_fields(result);
	MYSQL_ROW row;
	while ((row = mysql_fetch_row(result)))
	{
		for(int i = 0; i < num_fields; i++)
		{
			 printf("%s ", row[i] ? row[i] : "NULL");
		}

		printf("\n");
	}
		
	mysql_free_result(result);                                                                           
	mysql_close(conn);                                                                                 
	return EXIT_SUCCESS;                                                                               
}

Compile And Execute

gcc -o sql sql.c $(mariadb_config --include --libs)
./sql

MySQL Database Table Structure
PhpMyAdmin Displaying MySQL Database Students Structure

MySQL Database Table Data
PhpMyAdmin Displaying MySQL Database Students Data

C MySQL Select
Geany IDE Displayed C MySQL Select Code

C MySQL Select Result
Geany IDE Displayed C MySQL Select Result


Usage

You can use any IDE or text editor and the command line to compile and execute C code. In this tutorial, the OjamboShop.com Learning Python Course and Learning PHP completion inspired the database connection.

Open Source

GCC is licensed under the GNU General Public License version with the GCC Runtime Library Exception, version 3.1. This allows commercial use, modification, distribution, and allows making derivatives proprietary.

Learn Programming Courses:

Courses are optimized for your web browser on any device.

OjamboShop.com Learning Python Course
OjamboShop.com Learning Python Interactive Online Course

OjamboShop.com Learning PHP Course
OjamboShop.com Learning PHP Interactive Online Course

Limited Time Offer:

OjamboShop.com is offering 20% off coupon code SCHOOL for Learning Python Course or for Learning PHP Course until End Day 2024.

Learn Programming Ebooks:

Ebooks can be downloaded to your reader of choice.

OjamboShop.com Learning Python Ebook
OjamboShop.com Learning Python Ebook Cover Page

OjamboShop.com Learning PHP Ebook
OjamboShop.com Learning PHP Ebook With Sample Page

Conclusion:

GCC makes it easy for C to perform database connections using the MySQL Connector. The MySQL header must be included in order to perform MySQL functions including the procedure to select database data.

Take this opportunity to learn the Python or PHP programming language by making a one-time purchase at Learning Python Course or Learning PHP Course. A web browser is the only thing needed to learn Python or PHP in 2024 at your leisure. All the developer tools are provided right in your web browser.

If you prefer to download ebook versions for your reader then you may purchase at Learning Python Ebook or Learning PHP Ebook

References: