In our web application, although PHP, JSP and other scripts have provided the MySQL interface, but obviously directly using C language has better security and performance, in this article can be reflected.
First look at the structural body:
The following code block is used to connect the database communication process, to connect MySQL, you must establish a MySQL instance, through the Mysql_init initialization to start the connection.
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 represents the result of a query that returns rows (SELECT, show, DESCRIBE, EXPLAIN). The returned data is called a "dataset", the friend who used the database should be able to query the database after the result set is not unfamiliar, in the API of C corresponding is mysql_res, read data from the database, and finally read data from the 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 long lengths;/Column length s of current row *
/MYSQL handle/For unbuffered reads/
my_bool EOF;/* Used my mysql_fetch_row */
} my Sql_res;
--------------------------------
Look at the function again:
C language Operation MySQL data common functions
Required headers: #include <mysql/mysql.h> function: Get or initialize a MySQL structure function prototype: MySQL *mysql_init (MySQL *mysql) function return value: A mysql* handle note that was started: In the case of low memory, returns the required header file for null: #include <mysql/mysql.h> function function: Turn off a server connection and free the connection-related memory function prototype: void Mysql_close (MySQL *mysql)
; Function incoming value: MySQL: type of pointer function return value: No required headers: #include <mysql/mysql.h> function function: Connect a MySQL server function prototype: MySQL * mysql_connect (MySQL *m
Ysql,const Char *host,const char *user,const char *passwd);
function passed in value: MySQL represents an existing MySQL structure address host indicates that the MySQL server's hostname or IP user represents the logged-on user name passwd the password function return value of the login: If the connection succeeds, a MySQL * connection handle: If the connection fails, NULL Note: This function is not recommended, using Mysql_real_connect () instead of the required files: #include <mysql/mysql.h> functions: 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 passed in value: MySQL represents an existing MySQL structure address host indicates that the MySQL server's hostname or IP user represents the logged-on user name passwd indicates that the login's password db indicates the database port to connect to represents the MySQL server's TCP/IP ports UN Ix_socket represents the connection type Client_flag represents the return value of a token function for MySQL running an ODBC database: If the connection succeeds, a mysql* connection handle: If connection fails, NULL required header file: #include <mysql/mysql.h> function function: Returns the most recent update,delete or insert query-affected number of rows function passed in value: MySQL: Type pointer function return value: An integer greater than 0 represents the number of rows affected or retrieved.
Zero indicates that there is no record of the WHERE clause in the region-matching lookup or that no query has been executed;-1 indicates that the query returned an error or the required header file for a select query: #include <mysql/mysql.h> function function: Execute a query on a specified connection
Function prototype: int mysql_query (mysql *mysql,const char *query);
Function pass in value: query represents the executed SQL statement function return value: If the query succeeds, zero, the error is non-zero. Related functions: Mysql_real_query required header file: #include <mysql/mysql.h> function function: Obtain the result identifier function for the result set without buffering the prototype: Mysql_res *mysql_use_result (
MYSQL *mysql); Function incoming value: MYSQL: Type of pointer function return value: A mysql_res result structure, if an error occurs NULL #incluee <mysql/mysql.h> retrieves the next line of a result set Mysql_row Mysql_
Fetch_row (Mysql_res *result); Mysql_res: A mysql_row structure in the next line of the pointer to the structure.
If there are no more rows to retrieve or if an error occurs, NULL #include <mysql/mysql.h> returns the number of columns in the specified result set unsigned int mysql_num_fields (mysql_res *res); An unsigned integer #include the number of fields in the pointer result collection of the mysql_res structure <mysql/mysql.h> create a database int mysql_create_db (MySQL *mysql,const char *db
);
MYSQL: Type of pointer db: The name of the database to create if the database is successfully created, return zero, or Non-zero if an error occurs. #include <mysql/mysql.h> Select adatabase int mysql_select_db (MySQL *mysql,const char *db);
MYSQL: Type of pointer db: The name of the database to create if the database is successfully created, return zero, or Non-zero if an error occurs.
----------------------------------------------
--------------
Look again at the example:
Many people use MySQL to develop some projects, sometimes for performance, we will directly use C language to develop related modules, especially in our web applications, although PHP, JSP and other scripts have provided the MySQL interface, but obviously directly using the C language has better security and performance, This type of interface, written in C, was used in several projects that Michael used to develop in PHP. And then compiled into PHP, for PHP script directly use, this aspect of the topic is not much said, the following is mainly about how to use the C language in Linux to connect the MySQL database, and read inside the Data is returned and how it is compiled.
Most of the code here refers to the MySQL release package of the. C source file, you can also go inside to find the relevant code, the following code to achieve the connection to the local MySQL server 9tmd_bbs_utf8 database, from the datasheet tbb_ User obtains the username of the user according to the input userid and prints the output to the terminal.
#if defined (_WIN32) | | Defined (_win64)//To support the compilation #include <windows.h> #endif #include <stdio.h> #include on the Windows platform <stdlib.h > #include "mysql.h"///On my machine the file is under/usr/local/include/mysql//defines a macro for database operations, or it can be left to write directly into the code #define SELECT_QUERY " Select username from tbb_user where UserID =%d "int main (int argc, char **argv)//char **argv equivalent to char *argv[] {MYSQL Mysql,*sock; Defines a handle to the database connection, which is used for almost all MYSQL functions mysql_res *res; Query result set, structure type Mysql_field *fd; structure that contains field information Mysql_row ROW; String array char qbuf[160] that holds a row of query results;
Hold query SQL statement string if (argc!= 2) {//Check input parameter fprintf (stderr, "Usage:mysql_select <userid>\n\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\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 joining this row}
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, depending on your environment
When running, execute the following command
./mysql_select 1
The following results will be returned:
Number of fields Returned:1
ther userid #1 ' s username is:michael
Query OK!
The above is the entire content of this article, I hope to help you learn.