After MySQL is installed, an include directory and a lib directory are generated under mysql. The include directory holds the header file, and the lib is the dynamic link library. Copy mysql.h under include / to / usr/include, and copy libmysqlclient.so and libmysqlclient.so.18 under lib / to / usr/lib64. The writing program needs to include the mysql.h header file. Add - lmysqlclient when linking
The source code is connect.c, where all the header files are placed under the /usr/include/mysql file. The principle is very simple. First initialize a handle, then call the connection function and pass in the username and password. Here, connect to the database named "wz" and "wz", and query all the data as follows:
#include <stdio.h> #include <mysql/mysql.h> #include <string.h> void main() { MYSQL mysql; MYSQL_RES *res = NULL; MYSQL_ROW row; char *query_str = NULL; int rc, i, fields; int rows; /* Initialization handle */ if (NULL == mysql_init(&mysql)) { printf("mysql_init() : %s\n", mysql_error(&mysql)); return; } /* Establish connection with database */ if (NULL == mysql_real_connect(&mysql, "localhost", "root", "123456", "wz", 0, NULL, 0)) { printf("mysql_real_connect() : %s\n", mysql_error(&mysql)); return; } printf("connect mysql successful\n"); /* Set character set to uft8 to support Chinese */ if (mysql_set_character_set(&mysql, "utf8")) { printf("mysql_set_character_set(): %s\n", mysql_error(&mysql)); return; } /* Set query statement */ query_str = "select * from wz"; rc = mysql_real_query(&mysql, query_str, strlen(query_str)); if (rc != 0) { printf("mysql_real_query() : %s\n", mysql_error(&mysql)); return; } /* Reception result */ res = mysql_store_result(&mysql); if (NULL == res) { printf("mysql_store_result(): %s\n", error(&mysql)); return; } /* Get rows and columns */ rows = mysql_num_rows(res); printf("The total rows is: %d\n", rows); fields = mysql_num_fields(res); printf("The total fields is: %d\n", fields); /* Print all attributes in circular row and column */ while ((row = mysql_fetch_row(res))) { for (i = 0; i < fields; i++) { printf("%s\n", row[i]); } printf("\n"); } /* Disconnect */ mysql_close(&mysql); }
The implementation effect is as follows:
[root@1dot1dot1dot1 mysql]# ./start.sh connect mysql successful The total rows is: 3 The total fields is: 4 1 //Study edward 2018-09-13 9 //work edward 2018-09-14 12 //entertainment james 2018-09-14
Directly use the command line to query the results as follows:
mysql> select * from wz; +----+--------+--------+------------+ | id | title | author | date | +----+--------+--------+------------+ | 1 | Study | edward | 2018-09-13 | | 9 | work | edward | 2018-09-14 | | 12 | entertainment | james | 2018-09-14 | +----+--------+--------+------------+ 3 rows in set (0.02 sec)
Operations such as adding and deleting are similar. Just call the corresponding api