Use the C language to operate MySQL databases first look at the structure: the following code block is used to connect to the database communication process, to connect to MYSQL, you must establish a MYSQL instance, through mysql_init initialization, you can start to connect to typedefstructst_mysql {NET using C language to operate MySQL database
First look at the struct:
The following code block is the communication process used to connect to the database. to connect to MYSQL, you must create a MYSQL instance and initiate the connection through mysql_init.
Typedef struct st_mysql {
NET net;/* Communication parameters */
Gptr connector_fd;/* ConnectorFd 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;
This structure returns the results of a query (SELECT, SHOW, DESCRIBE, or EXPLAIN) of a row. The returned data is called a "dataset". friends who have used the database should be familiar with the result set obtained after the database is queried. in api c, the returned data is MYSQL_RES, read data from the database, and finally read data from MYSQL_RES.
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 longLengths ;/Column lengths of current row */
MYSQLHandle ;/For unbuffered reads */
My_bool eof;/* Used my mysql_fetch_row */
} MYSQL_RES;
--------------------------------
Look at the function again:
Common functions for operating mysql data in C language
Required header file: # include
Function: obtain or initialize a MYSQL schema function prototype: MYSQL * mysql_init (MYSQL * mysql) function return value: A started MYSQL * handle remarks: when the memory is insufficient, return the header file required for NULL: # include
Function: Closes a server connection and releases the memory function prototype related to the connection: void mysql_close (MYSQL * mysql). input value of the function: MYSQL: type pointer function return value: no header file required: # include
Function: connect to a MySQL server function prototype: MYSQL * mysql_connect (MYSQL * mysql, const char * host, const char * user, const char * passwd); function input value: mysql represents an existing mysql structure address host represents the MYSQL server host name or IP user represents the login user name passwd represents the login password function return value: if the connection is successful, a MYSQL * connection handle: if the connection fails, NULL remarks: This function is not recommended. use mysql_real_connect () to replace the required File: # include
Function: MYSQL * 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 client_flag); input value of the function: mysql represents an existing mysql structure address host represents the MYSQL server host name or IP user represents the login user name passwd represents the login password db represents the database port to be connected represents the MySQL server TCP/IP the port unix_socket indicates the connection type client_flag, which indicates the flag returned value for MySQL to run the ODBC database: if the connection is successful, a MYSQL * connection handle: if the connection fails, the header file required for NULL: # include
Function: return the number of rows affected by the latest UPDATE, DELETE, or INSERT query. input value: MYSQL: type pointer function return value: an integer greater than zero to indicate the number of rows affected or retrieved. Zero indicates that there is no record of the WHERE clause in the partition query order or no query is executed yet;-1 indicates that an error is returned for the query or the header file required for a SELECT query: # include
Function: runs the query function prototype for the specified connection: int mysql_query (MYSQL * mysql, const char * query); input value of the function: query indicates the return value of the executed SQL statement function: if the query is successful, it is zero, and the error is non-zero. Related functions: header files required for mysql_real_query: # include
Function: obtain the result identifier for a result set without buffering function prototype: MYSQL_RES * mysql_use_result (MYSQL * mysql); function input value: MYSQL: type pointer function return value: A MYSQL_RES result structure. If an error occurs, send NULL # deleee
Retrieve the next MYSQL_ROW mysql_fetch_row (MYSQL_RES * result) of a result set; MYSQL_RES: a MYSQL_ROW structure of the next row of the structure pointer. If no more rows can be retrieved or if an error occurs, NULL # include
Returns the number of columns in the specified result set unsigned int mysql_num_fields (MYSQL_RES * res); an unsigned integer # include
Create a database int mysql_create_db (MYSQL * mysql, const char * db); MYSQL: type pointer db: name of the database to be created. if the database is successfully created, zero is returned, if an error occurs, the value is non-zero. # Include
Select a database int mysql_select_db (MYSQL * mysql, const char * db); MYSQL: type pointer db: name of the database to be created. if the database is successfully created, zero is returned, if an error occurs, the value is non-zero.
----------------------------------------------
--------------
Let's look at the example:
Many people use MySQL to develop some projects. sometimes, for the sake of performance, we directly use C language to develop related modules, especially in our web applications, although PHP, JSP, and other scripts provide MySQL interfaces, it is clear that using C language directly has better security and performance, michael used to use this type of interface written in C language in multiple projects developed using PHP before compiling it into php for direct use by php scripts, I will not talk about this topic much. next I will mainly talk about how to connect to the MySQL database with C language in Linux, read the data returned in it, and compile it at the same time.
Most of the code here is referenced in the MySQL release package. c source file. you can also find the relevant code in it. the following code connects to the 9tmd_bbs_utf8 database on the local MySQL server, obtain the user name from the table tbb_user based on the input userid and print the user name to the terminal.
# If defined (_ WIN32) | defined (_ WIN64) // to support compilation on windows # include # Endif # include # Include # Include "mysql. h "// on my machine, the file is in the/usr/local/include/mysql // defines the macro for database operations, you can also leave it undefined and write it directly into the code # define SELECT_QUERY "select username from tbb_user where userid = % d" int main (int argc, char ** argv) // char ** argv is equivalent to char * argv [] {MYSQL mysql, * sock; // defines the database connection handle, which is used by almost all MySQL functions MYSQL_RES * res; // query result set, structure type MYSQL_FIELD * fd; // structure containing field information MYSQL_ROW row; // string array that stores the query result of a row char qbuf [160]; // store the query SQL statement string if (argc! = 2) {// Check the input parameter fprintf (stderr, "usage: mysql_select \ N "); exit (1) ;}mysql_init (& mysql); if (! (Sock = mysql_real_connect (& mysql, "localhost", "dbuser", "dbpwd", "9tmd_bbs_utf8", 0, NULL, 0) {fprintf (stderr, "Couldn't connect to engine! \ N % s \ n ", mysql_error (& mysql); perror (" "); exit (1) ;} sprintf (qbuf, SELECT_QUERY, atoi (argv [1]); if (mysql_query (sock, qbuf) {fprintf (stderr, "Query failed (% s) \ n", mysql_error (sock )); exit (1);} if (! (Res = mysql_store_result (sock) {fprintf (stderr, "Couldn't get result from % s \ n", mysql_error (sock); exit (1 );} printf ("number of fields returned: % d \ n", mysql_num_fields (res); while (row = mysql_fetch_row (res )) {printf ("Ther userid # % d's username is: % s \ n", atoi (argv [1]), (row [0] = NULL) &&(! Strlen (row [0])? "NULL": row [0]); puts ("query OK! \ N ") ;}mysql_free_result (res); mysql_close (sock); exit (0); return 0; //. to be compatible with most compilers, add this line}
When compiling, use the following command
Gcc-o mysql_select. /mysql_select.c-I/usr/local/include/mysql-L/usr/local/lib/mysql-lmysqlclient (-lz) (-lm) the following two options are optional, based on your environment
Run the following command
./Mysql_select 1
The following result is returned:
Number of fields returned: 1
Ther userid #1's username is: Michael
Query OK!
Most of the above code can be understood. if you do not understand it, refer to other articles on mysql database in this blog. the C language API functions are described in detail.