Database Reference
In-Depth Information
C API
The C language isn'tas popular as it once was, but it's still a standard. In fact, the core
software of MySQL is written in C. The C API is provided by MySQL. This section
provides a basic tutorial on how to connect to a database and how to query it with C and
the C API, the basic components and tasks you need to know to use this API.
Connecting to MySQL
When writing a C program tointeract with a database, first we need to prepare variables
that will store data on the database connection and the results of a query we intend to ex-
ecute. Then we will need to establish a connection to the server. To do this easily, we'll in-
clude a couple of C header files: stdio.h for basic C functions and variables, and mysql.h
for special MySQL functions and definitions (these two files come with C and MySQL, as
well as MariaDB; you shouldn't have to download them if C and MySQL were installed
properly on your server):
#include <stdio.h>
#include "/usr/include/mysql/mysql.h"
int main ( int argc , char * argv [ ])
{
MYSQL * mysql ;
MYSQL_RES * result ;
MYSQL_ROW row ;
...
The < and > symbols surrounding stdio.h tells C to look for the file in the default location
for C header files (e.g., /usr/include ), or in the user's path. Because mysql.h may not be in
the default locations, the absolute path is given within double quotes. An alternative here
would have been <mysql/mysql.h> , because the header file is in a subdirectory of the
default C header file directory.
The standard main function begins by preparing variables needed for the connection to
MySQL. The first line creates a pointer to the MYSQL structure stored in the mysql vari-
able. The next line defines and names a results set based on the definitions for
MYSQL_RES in mysql.h . The results are to be stored in the result array, which will be
an array of rows from MySQL. The third line of main uses the definition for MYSQL_ROW
to establish the row variable, which will be used later to contain an array of columns from
MySQL.
Having included the header files and set the initial variables, we can now set up an object
in memory for interacting with the MySQL server usingthe mysql_init() function:
Search WWH ::




Custom Search