The MySQL C API Programming Example

xiaoxiao2021-03-06  97

I found some Mysql C API programming articles, I think it is not enough to write, I wrote this "The MySQL C API Programming Instance" according to my own experience, I hope to call the API of the c to MySQL. Help, the environment in the example is redhat

In this article, we will learn how to use MySQL's C APIS (Application Programming Interfaces programming interface). In order to understand this article very well, you need to have the following premise knowledge:

C Language Variable C Language Function C Language Pointer

Introduction

C APIS is included in the MySQLClient library file, which is released with MySQL source code for connecting to the database and executes database queries. There are some examples in the clients directory of MySQL original code.

MySQL C variable type

The following variable type is defined in the library of MySQL. We need these variables to use MySQL's functions. These variables have been explained in detail, but these explanations are not important for writing code.

Mysql

The following code block is a communication process used to connect to the database. To connect to MySQL, you must establish a MySQL instance, and you can start by MySQL_INIT initialization. This will be said later.

TYPEDEF STRUCT ST_MYSQL {

Net Net; / * Communication Parameters * /

GPTR Connector_fd; / * connectionorfd for ssl * /

Char * Host, * User, * passwd, * unix_socket,

* Server_version, * Host_info, * info, * db;

Unsigned int port, client_flag, server_capabilities;

Unsigned int protocol_version;

Unsigned int field_count;

Unsigned int server_status;

Unsigned long thread_id; / * id for connection in server * /

MY_ULONGLONG Affected_Rows;

MY_ULONGLONG INSERT_ID; / * ID IF INSERT ON TABLE with NextNR * /

MY_ULONGLONG EXTRA_INFO; / * Used by mysqlshow * /

Unsigned long packet_length;

ENUM mysql_status status;

Mysql_field * fields;

MEM_ROOT FIELD_ALLOC;

MY_BOOL FREE_ME; / * if free in mysql_close * /

MY_BOOL Reconnect; / * set to 1 if Automatic Reconnect * /

Struct ST_MYSQL_OPTIONS OPTIONS;

Char scramble_buff [9];

Struct charset_info_st * charSet;

Unsigned int server_language;

} Mysql;

MySQL_RES

This structure represents the result of a query of the return line (SELECT, SHOW, DESCRIBE, EXPLAIN). The returned data is called "Dataset". Friends with the database should not be unfamiliar with the result set after the query in the database, and in the C's API is mysql_res, read the data from the database, and finally from mysql_res Read data.

TYPEDEF STRUCT ST_MYSQL_RES {MY_ULONGLONG ROW_COUNT

Unsigned int field_count, current_field;

Mysql_field * fields;

Mysql_data * data;

Mysql_rows * data_cursor;

MEM_ROOT FIELD_ALLOC;

MySQL_Row Row; / * if unbuffered read * /

MySQL_ROW CURRENT_ROW; / * BUFFER TO CURRENT ROW * /

Unsigned long * lengths; / * column lengths of current row * /

MySQL * Handle; / * for unbuffered reads * /

MY_BOOL EOF; / * USED my mysql_fetch_row * /

} Mysql_res;

MySQL_ROW

This is the representation of the type of line data (type-way). It is currently implemented as a number of bytes of string arrays. (If the field value may contain binary data, you cannot treat these as an air stop string, because such values ​​can be included in the internal block by call mysql_fetch_row () by calling mysql_fetch_row ().

TYPEDEF CHAR ** mysql_row;

MySQL_Field

This structure contains field information, such as field name, type, and size. Its members are described in more detail below. You can get the mysql_field structure for each column by repeating mysql_fetch_field (). The field value is not part of this structure; they are included in a mysql_row structure.

Typedef struct ST_MYSQL_FIELD {

Char * name; / * name of column * /

Char * Table; / * Table of column if column was a field * /

Char * Def; / * Default value (set by mysql_list_fields) * /

Enum enum_field_types type; / * type of field. SE mysql_com.h for types * /

Unsigned int layth; / * width of colorn * /

Unsigned int max_length; / * max width of successd set * /

Unsigned int flags; / * div flashs * /

Unsigned int decimals; / * number of decimals in field * /

} Mysql_field;

MY_ULONGLONG

Typedef unsigned long my_ulonglong;

This type is used for row number and mysql_affected_rows (), mysql_num_rows (), and mysql_insert_id (). This type provides a range of 0 to 1.84E19. On some systems, trying to print the value of MY_ULONGLONG will not work. In order to print such a value, transform it to the unsigned long and use one% Lu print format. E.g:

Printf (NUMBER OF ROWS:% lu / n ", (unsigned long) mysql_num_rows (result));

Connect mysql, query data

Now assume that mysql is installed, users and data sheets are created in the database. For the case of preventing anything unknown, please refer to the www.mysql.com website. As mentioned earlier, the library of mysql is in mysqlclient. Therefore, it is necessary to add -LMYSQLCLIENT compilation option when compiling the MySQL program. MySQL's header file in / usr / include / mysql directory (depending on the release version of Linux, this directory is different), so your program head looks a bit:

#include

MySQL variable types and functions are included in this header file

Then, we need to create variables that connect to the database, you can simply do this:

Mysql mysql;

Before connecting the database, we want to call the following function to initialize this variable:

MySQL_INIT (& mysql);

Then, call mySQL_REAL_CONNECT functions:

MySQL * stdcall mysql_real_connect (mysql * mysql, const char * host,

Const char * User,

Const char * passwd,

Const char * DB,

Unsigned int port,

Const char * unix_socket,

Unsigned int clientflag;

This function is called to the database. Host is the host name of the MySQL server, User is the username of the login. The passwd is the login password. DB is the database to connect. Port is the TCP / IP port of the MySQL server. Unix_socket is the connection type, and the clientflag is mysql runs into an ODBC database mark. In this article, the tag is set to 0. After the connection is established, this function returns 0.

Now you can connect the database, check:

Char * query;

Using this string we can create any SQL query statements for query. The function to perform this query is:

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

MySQL is the variable we used in front, Q is the SQL query statement, and Length is the length of this query statement. If the query is successful, the function returns 0.

After the query, we have to go to a mysql_res variable to use the result of the query. This line created this variable:

Mysql_res * res;

then

RES = mysql_store_result (& mysql);

For the client, there are two ways to process the result collection. One method is to retrieve all results immediately by calling mysql_store_result (). This function gets all rows returned from the server and stores them on the client. The second method is to initialize the retrieval of a row of one line of row of row results to customers by calling Mysql_Use_Result (). This function is initialized to retrieve, but it does not actually get any rows from the server.

In both cases, you have row via mysql_fetch_row (). Use mysql_store_Result (), mysql_fetch_row () stores the row that has been removed from the server. Use mysql_use_result (), mysql_fetch_row () actually retrieve line from the server. Call mysql_fetch_lengths () to obtain information about data value size per row.

After you run a result collection, call mysql_free_result () release the memory it uses.

Two search mechanisms are complementary. The client should choose the way to best suggest them. In practice, customers are usually more willing to use mysql_store_result (). This function reads out the results of the query.

Although it can be easily queried, the results of this query should be used to use other functions. the first is:

MySQL_ROW stdcall mysql_fetch_row (mysql_res * result);

This function converts the result into an "array." You may notice that the function returns the mysql_row variable type. The following statement creates such variables:

Mysql_row rotion = mysql_fetch_row (res)

As explained above, the variable row is a string array. That is, ROW [0] is the first value of the array, and the Row [1] is the second value of the array ... When we use mysql_fetch_row, the variable ROW will acquire the next set of data. When the end of the result, the function returns a negative value.

After the end of the data set, remember to release the data set, otherwise the memory leak will occur, the release data set function is as follows:

Void mysql_free_result (mysql_res * result)

Release is allocated by mysql_store_result (), mysql_use_result (), mysql_list_dbs () or the like as a result collection. When you run out of a result collection, you must call mysql_free_result () to release the memory it uses.

Finally, we have to close this connection:

MySQL_Close (& mysql);

Example program

Perform a SELECT operation, take data from the database, and execute an insert operation, insert data into the database, according to these two operations you can freely expand to any database operation,

Preparation conditions

1. Mysql has been installed, there is a database Test, if not executed

Create Database Test

build database

2, Test database has table T1, if not, execute

Create Table `T1` (

`ID` int (11) default null,

`Name` VARCHAR (100) Default NULL

)

Establish table T1

Testsql.c:

/ * Testsql.c

** An Example To Use MySQL C API

** Copyright 2004 Coon XU.

** Author: coon Xu

** Date:

05 NOV 2004

* /

#include

#include

Int main () {

Mysql mysql; // neied a instance to init

Mysql_res * res;

Mysql_row rotion;

Char * query;

INT T, R;

// Connect The Database

MySQL_INIT (& mysql);

IF (! Mysql_Real_Connect (& Mysql, "Localhost", "MMIM", "MMIM", "TEST", 0, NULL, 0))

{

Printf ("Error Connecting to Database:% S / N", MySQL_ERROR (& mysql));

}

Else Printf ("Connected ... / N");

// get the result from the executing Select Query

Query = "SELECT * from T1"; T = mysql_real_query (& mysql, query, (unsigned int) Strlen (query);

IF (t)

{

Printf ("Error Making Query:% S / N",

mysql_error (& mysql));

}

Else Printf ("[% s] Made ... / n", query);

RES = mysql_store_result (& mysql);

While (row = mysql_fetch_row (res))

{

For (t = 0; t

{

Printf ("% s", row [t]);

}

Printf ("/ n");

}

Printf ("MySQL_FREE_RESULT ... / N");

MySQL_Free_Result (res); // Free Result After You Get The Result

Sleep (1);

// Execute the insert query

Query = "INSERT INTO T1 (ID, NAME) VALUES (3, 'KUNP')"

T = mysql_real_query (& mysql, query, (unsigned int) Strlen (query);

IF (t)

{

Printf ("Error Making Query:% S / N",

mysql_error (& mysql));

}

Else Printf ("[% s] Made ... / n", query);

MySQL_Close (& mysql);

Return 0;

}

Compile

Assuming the MySQL's header file in / usr / include / mysql, library files in / usr / lib / mysql, perform the following command to compile:

GCC Testsql.c -i / usr / include / mysql -l / usr / lib / mysql -lmysqlclient

转载请注明原文地址:https://www.9cbs.com/read-95903.html

New Post(0)