MySQL C API programming: The MySQL programming interface written in C language

Source: Internet
Author: User
Tags empty functions header connect mysql socket version variable

In software development, we often have access to the database, access to data, before there have been friends to Peck Rice to tell the knowledge of the database programming, this article explains how to use the MySQL C language API for database programming.

API, full name application programming interfaces, the application programming interface, we can invoke these interfaces to perform functions provided by API functions.

MySQL C language API is written in C language of the MySQL programming interface, the use of these interface functions can be implemented on the MySQL database queries and other operations.

installation of MySQL

To do MySQL programming first in the MySQL server as a computer and on this machine are installed MySQL, the server MySQL used to connect the query, the computer on the MySQL as a development, of course, the machine can also take into account the server and development. MySQL can be downloaded to Chicken Peck rice is installed in the "Windows (x86, 64-bit), MSI Installer" version.

During the MySQL installation, the installation option must be selected to the client C API library (shared) under development components to install the MySQL API header and dynamic libraries onto the computer.

After the installation is complete, we are programmed to use the header files in the Include directory and the library files in the Lib directory.

Mysql API Data Structure

MySQL API used a lot of data types such as structure, the following simple to say the meaning of several data structures commonly used, as for their definition of the chicken peck rice will not be affixed, you can go to the MySQL provided by the mysql.h header files to view.


Before you can connect to a database, you must first create a MySQL variable, which is used in many MySQL API functions. It contains some data such as connection information.


The Mysql_res structure Body contains the query result set, which is the data that is queried from the database. Can be obtained using the Mysql_store_result or Mysql_use_result functions.


The MYSQL row is defined as follows:

typedef char **mysql_row;

Visible, it is actually a char * * type, pointing to an array of strings. Can be obtained through the Mysql_fetch_row function.


The Mysql_field contains information such as field names, field types, and sizes. You can call the Mysql_fetch_field function repeatedly to get information about all the fields.

Mysql C API Programming steps

1, first we want to include MySQL header file, and link MySQL dynamic library. The following statement is added:

#include //network programming needs Winsock2.h


#pragma comment (lib, "Libmysql.lib")

2, create MySQL variable. Such as:


3, initialize the MySQL variable.

Mysql_init (&mysql);

4, call the Mysql_real_connect function to connect the MySQL database. The prototype of the Mysql_real_connect function is as follows:

MySQL * stdcall mysql_real_connect (MySQL *mysql, const char *host,const char *user,const char *passwd,const char *db,unsig Ned Int Port,const Char *unix_socket,unsigned long clientflag);

Parameter description: mysql--the MySQL variable previously defined, Host--mysql server address, user--login username, passwd--login password, db--database to connect to, Port--mysql server TCP service port; unix_ Socket--unix connection mode, NULL when the socket or pipe mechanism is not used; Clientflag--mysql runs as a token for an ODBC database, typically 0. This function returns 0 when the connection fails.

5, call the Mysql_real_query function for database query. The prototype of the Mysql_real_query function is as follows:

int stdcall mysql_real_query (MySQL *mysql, const char *q, unsigned long length);

Parameter description: mysql--the MySQL variable previously defined, Q--SQL query statement, length--query statement length.

The function returns 0 if the query succeeds.

6. Get the query result data by calling the Mysql_res variable returned by the Mysql_store_result or Mysql_use_result function.

The prototypes for the two functions were:

Mysql_res * stdcall mysql_store_result (MySQL *mysql);

Mysql_res * stdcall mysql_use_result (MySQL *mysql);

These two functions represent two ways to get the results of a query. First, call the Mysql_store_result function to store all the data that is queried from the MySQL server to the client and then read; the second, call Mysql_use_result to initialize the retrieval so that the result set can be read on the next line. It does not itself read any data from the server, which is faster and requires less memory than the first, but it binds the server, prevents other threads from updating any tables, and must repeatedly perform mysql_fetch_row read data until NULL is returned. Otherwise, the unread rows are returned as part of the result at the next query, so we often use mysql_store_result.

7, call the Mysql_fetch_row function to read the result set data.

The last two ways are to repeatedly call the Mysql_fetch_row function to read the data. The prototype of the Mysql_fetch_row function is as follows:

Mysql_row stdcall mysql_fetch_row (mysql_res *result);

The parameter result is the return value of the Mysql_store_result or Mysql_use_result.

The function returns the variable of type Mysql_row, which is an array of strings, assumed to be row, then Row[i] is the value of the first field. This function returns NULL when the tail of the result set is returned.

8. After the result set is exhausted, call the Mysql_free_result function to release the result set to prevent memory leaks. The prototype of the Mysql_free_result function is as follows:

void StdCall mysql_free_result (mysql_res *result);

9, no longer query the MySQL database, call the Mysql_close function to close the database connection. The prototype of the Mysql_close function is:

void StdCall mysql_close (MySQL *sock);

Mysql C API Programming Example

Here's a simple example of MySQL API programming. Write using VS2010. The database accessed is a database that is created by default after MySQL is installed, and queries its "User" table for data in the following steps:

1, create a WIN32 console application (WIN32 console program) of the Empty project (to create an empty project in the wizard application settings step, check Empty project), the name is taken as MySQL.

2, in the Solution Explorer window project name "MySQL" on the right click, select "Properties", pop-up project property page, and then in the Left child window, select configuration properties->vc++ directories, the Right child window displays a list of settings items, and then adds the MySQL include directory in the Include Directories entry and adds the MySQL Lib directory to the library directories entry.

3, a new CPP file, named Mysql.cpp.

4, in the Mysql.cpp file contains MySQL header file and link MySQL dynamic library.



#pragma comment (lib, "Libmysql.lib")

Note here that because MySQL uses the interface functions of a network connection, you need to include the WinSock2.h file in the front.

At the same time, the output stream cout is used in this example, so also include the input output stream header file:


using namespace Std;

5. Create the main function and modify the function body as follows:

int main ()



Mysql_res *res;

Mysql_row ROW;

Initializing MySQL variables

Mysql_init (&mysql);

Connect to the MySQL server, this example uses this machine as the server. Access to the database name "MSYQL", the user in the parameter for your login username, * * * for the login password, need to be based on your actual user settings

if (! Mysql_real_connect (&mysql, "", "User", "123", "MySQL", 3306, 0, 0))


cout << "Mysql_real_connect failure! "<< Endl;

return 0;


Querying the user table in a MySQL database

if (Mysql_real_query (&mysql, "SELECT * from User", (unsigned long) strlen ("SELECT * from user"))


cout << "Mysql_real_query failure! "<< Endl;

return 0;


Storing result Sets

res = Mysql_store_result (&mysql);

if (NULL = = res)


cout << "Mysql_store_result failure! "<< Endl;

return 0;


Reads the row repeatedly and prints the value of the first field until row is null

while (row = mysql_fetch_row (res))


cout << row[0] << Endl;


Releasing the result set

Mysql_free_result (RES);

Close MySQL Connection

Mysql_close (&mysql);

return 0;


6. Copy the Libmysql.dll dynamic library files in the MySQL installation directory to the current directory of the project and run the program.

If you're using a 64-bit version of MySQL like a chicken peck, at this point the program will be an error, there are a lot of symbols can not be resolved, this is because our project is 32-bit, should be changed to 64-bit, method, the above Engineering property page in the upper right corner of the Configuration Manager button, Click it to eject the Configuration Manager dialog box, and the following list shows our project, platform column is displayed as "Win32":

Here you need to click the arrow on the right to pull down, select new to pop up the new Project Platform dialog box, and select x64 to create a platform:

The above platform column chooses x64 to be OK. Run the program again, and you'll find that it's not an error.

This article is here, so everyone should have a basic understanding of the MySQL C API programming, in the actual development can be continuously in-depth study.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.