Getting started with Mysql C language API programming

Source: Internet
Author: User

Original: Mysql C Language API programming introductory explanation

Software development we often have to access the database, access to data, has been put forward to let the chicken peck rice to talk about database programming knowledge, this article explains in detail how to use the MySQL C language API for database programming.

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

MySQL C language API is written in C language MySQL programming interface, using these interface functions can be implemented to the MySQL database query and other operations.

installation of MySQL

To do MySQL programming first in the computer as a MySQL server and the local installation of MySQL, the server of MySQL to connect the query, the local MySQL as a development, of course, the machine can also take into account the server and development. Download MySQL can go to http://www.mysql.com/downloads/mysql/. Chicken Peck rice is installed in the "Windows (x86, 64-bit), MSI Installer" version.

During the MySQL installation process, the installation option must be selected on the Client C API library (shared) under development components to install the MySQL API header and dynamic libraries into 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 structure and other data types, the following is a brief talk about the meaning of a few commonly used data structures, as to their definition chicken peck rice will not be affixed, we can go to MySQL provided by the mysql.h header file to view.

Mysql

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

Mysql_res

The mysql_res structure 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 function.

Mysql_row

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.

Mysql_field

Mysql_field contains information such as field name, field type, and size. You can call the Mysql_fetch_field function repeatedly to get information about all fields.

Mysql C API Programming steps

1, first we want to include MySQL header file, and link MySQL dynamic library. That is, add the following statement:

#include <WinSock2.h>//network programming required Winsock2.h

#include <mysql.h>

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

2. Create a MySQL variable. Such as:

MySQL MySQL;

3. Initialize the MySQL variable.

Mysql_init (&mysql);

4. Call the Mysql_real_connect function to connect to the MySQL database. The Mysql_real_connect function is prototyped 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 previously defined MySQL variable, host--mysql server address, user--login user name, passwd--login password, db--database to connect to, Port--mysql server TCP service port; unix_ Socket--unix connection mode, NULL indicates that the socket or pipe mechanism is not used; Clientflag--mysql runs as an ODBC database token, typically taking 0. The function returns 0 when the connection failsTOEFL Answers

5, call mysql_real_query function for database query. The Mysql_real_query function is prototyped as follows:

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

Parameter description: mysql--the previously defined MySQL variable; q--sql query statement; length--the length of the query statement.

The function returns 0 if the query succeeds.

6. Get 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 query results, respectively. First, call the Mysql_store_result function to store all data queried from the MySQL server to the client and then read, and the second, call Mysql_use_result to initialize the retrieval so that the result set is read in the next row, Instead of reading any data from the server itself, it is faster and requires less memory than the first, but it binds the server, prevents other threads from updating any tables, and must repeatedly execute mysql_fetch_row to read the data until NULL is returned. Otherwise, rows that are not read are returned as part of the result at the next query, so we often use Mysql_store_resultIELTS Answer

7. Call the Mysql_fetch_row function to read the result set data.

Both of these methods end up repeating calls to the Mysql_fetch_row function to read the data. The Mysql_fetch_row function is prototyped as follows:

Mysql_row stdcall mysql_fetch_row (mysql_res *result);

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

The function returns a variable of type Mysql_row, that is, a string array, assuming row, then Row[i] is the value of the I field. This function returns NULL when the end of the result set is reached.

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

void StdCall mysql_free_result (mysql_res *result);

9. When you 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 is a simple example of MySQL API programming. Written using VS2010. The database accessed is the database named "MySQL" created by default after installing MySQL, and the following steps are queried for the data of its "user" table:

1. Create an empty project for the WIN32 console application (Win32 console program) (to create an empty project you need to check empty project in the application settings step of the wizard), the name is MySQL.

2. Right-click on the project name "MySQL" On the Solution Explorer window, select "Properties", pop up the project's property page, and in the left Subwindow, select configuration properties->vc++ Directories, a list of settings is displayed in the Right child window, and the Include directory for MySQL is added to the Include directories item, and the MySQL Lib directory is added to the library directories item.



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

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

#include <WinSock2.h>

#include <mysql.h>

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

It is important to note that because MySQL uses the interface functions of the network connection, it needs to include the WinSock2.h file in front of it.

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

#include <iostream>

using namespace Std;

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

int main ()

{

MySQL MySQL;

Mysql_res *res;

Mysql_row ROW;

Initializing MySQL variables

Mysql_init (&mysql);

To connect to the MySQL server, this example uses this machine as a server. The database name of the access is "MSYQL", the user in the parameter is your login username, * * * login password, need to be based on your actual user settings

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

{

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

return 0;

}

Querying the user table in the 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 rows repeatedly and outputs 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 file from the MySQL installation directory to the current directory of the project and run the program.

If you are using the 64-bit version of MySQL as a chicken peck, the program will error, there are many unresolved symbols, this is because our project is 32-bit, should be changed to 64-bit, the method is that the upper right corner of the project property page above has a Configuration Manager button, Click on it to pop up the Configuration Manager dialog box, and the list below shows our project, the Platform column is "Win32":



Here you need to click on the arrow drop-down on the right, select new to pop up the new Project Platform dialog box, platform Select x64 to create the platform:



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

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

Getting started with Mysql C language API programming

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: info-contact@alibabacloud.com 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.