Use C language to operate MySQL Databases-General edition and general edition of mysql Databases

Source: Internet
Author: User
Tags mysql functions

Use C language to operate MySQL Databases-General edition and general edition of mysql Databases
Use C to operate MySQL Databases

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 <mysql/mysql. h> function: obtain or initialize a MYSQL schema function prototype: MYSQL * mysql_init (MYSQL * mysql) function return value: A started MYSQL * handle remarks: if the memory is insufficient, return the header file required for NULL: # include <mysql/mysql. h> function: close a server connection and release the memory function prototype related to the connection: void mysql_close (MYSQL * mysql); input function value: MYSQL: Type pointer function return value: no header file required: # include <mysql/mysql. h> function: connect to a MySQL server function prototype: MYSQL * mysql_connect (MYSQL * mysql, const char * host, const char * user, const char * passwd); input value of the function: m Ysql 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 <mysql/mysql. h> 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); function input value: mysql represents an existing mysql structure address host represents the MYSQL server host Name or IP user indicates the Login user Name passwd indicates the login password db indicates the database port to connect to, indicating the MySQL server's TCP/IP port unix_socket indicates the connection type client_flag indicates the mark of MySQL running ODBC database function return value: if the connection is successful, a MYSQL * connection handle: if the connection fails, the header file: # include <mysql/mysql. h> 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 indicates the number of affected or retrieved rows. 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 <mysql/mysql. h> function: runs the query function prototype for the specified connection: int mysql_query (MYSQL * mysql, const char * query); input function value: 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 <mysql/mysql. h> 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 # incluee <mysql/mysql. h> 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 <mysql/mysql. h> return the number of columns in the specified result set: unsigned int mysql_num_fields (MYSQL_RES * res); an unsigned integer # include <mysql/mysql. h> 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 <mysql/mysql. h> 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 platforms # include <windows. h> # endif # include <stdio. h> # include <stdlib. h> # 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 a row of query results char qbuf [160]; // store the query SQL statement string if (argc! = 2) {// check the input parameter fprintf (stderr, "usage: mysql_select <userid> \ 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.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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: 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.