C-language operation MySQL Database

Source: Internet
Author: User
Tags function prototype mysql functions php script

Original Author Blog http://www.cnblogs.com/nliao/archive/2010/09/09/1822660.html

First look at the structure

----------------------------------------------

The following code block is used to connect to the database of the communication process, to connect to MySQL, you must establish a MySQL instance, through the Mysql_init initialization can 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 a row SELECT SHOW DESCRIBE EXPLAIN . The returned data is called the "DataSet", the friend who used the database should not be unfamiliar with the result set in the database, the corresponding in the C API is Mysql_res, reading from the database, and finally reading the 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 lengths of current row */
MYSQL *handle; /* for unbuffered reads */
My_bool EOF; /* Used my mysql_fetch_row */
} mysql_res;

----------------------------------------------

Look at the function again:

C language Operation MySQL data common functions

Required header files: #include <mysql/mysql.h>
Function: Get or initialize a MySQL structure
Function prototypes: MySQL *mysql_init (MySQL *mysql)
function return value: A mysql* handle that is initialized
Note: null is returned in case of low memory

Required header files: #include <mysql/mysql.h>
function function: Close a server connection and release the memory associated with the connection
Function prototype: void Mysql_close (MySQL *mysql);
function passed in value: MYSQL: pointer of type
function return value: None

Required header files: #include <mysql/mysql.h>
function function: Connect a MySQL server
Function prototype: MySQL * mysql_connect (mysql *mysql,const char *host,const char *user,const char *passwd);
function passed in value: MySQL represents an existing MySQL structure address
Host indicates the hostname or IP of the MySQL server
User name for Login
PASSWD indicates the password of the login
function return Value: If the connection succeeds, a MySQL * connection handle: NULL If the connection fails
Note: This function is not recommended, use Mysql_real_connect () instead

Required Documents: #include <mysql/mysql.h>
function 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 passed in value: MySQL represents an existing MySQL structure address
Host indicates the hostname or IP of the MySQL server
User name for Login
PASSWD indicates the password of the login
DB indicates the database to connect to
Port indicates the TCP/IP port of the MySQL server
Unix_socket indicates the connection type
Client_flag indicates that MySQL is running the ODBC database tag
function return Value: If the connection succeeds, a mysql* connection handle: NULL If the connection fails

Required header files: #include <mysql/mysql.h>
function function: Returns the number of rows affected by the most recent update,delete or insert query
function passed in value: MYSQL: Type pointer
function return value: An integer greater than 0 indicates the number of rows affected or retrieved. Zero indicates that there is no record of the WHERE clause in the lookup sequence or that no query has been executed yet;-1 indicates that the query returned an error, or for a select query

Required header files: #include <mysql/mysql.h>
function function: Execute a query on the specified connection
Function prototype: int mysql_query (mysql *mysql,const char *query);
function passed in value: query represents the SQL statement executed
function return value: If the query succeeds, zero, the error is nonzero.
Correlation function: Mysql_real_query

Required header files: #include <mysql/mysql.h>
function function: Obtain the result identifier for the unbuffered result set
Function prototype: Mysql_res *mysql_use_result (MYSQL *mysql);
function passed in value: MYSQL: pointer of type
function return value: A mysql_res result structure, if an error occurs, a null is sent

#incluee <mysql/mysql.h>
Retrieves the next row of a result collection
Mysql_row mysql_fetch_row (Mysql_res *result);
Mysql_res: Pointers to structures
A mysql_row structure for the next line. 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);
Pointers to Mysql_res structures
An unsigned integer of the number of fields in the result collection

#include <mysql/mysql.h>
Create a database
int mysql_create_db (MySQL *mysql,const char *db);
MYSQL: pointer of type
DB: The name of the database to be created
If the database was successfully created, zero is returned, and nonzero if an error occurs.

#include <mysql/mysql.h>
Select a database
int mysql_select_db (MySQL *mysql,const char *db);
MYSQL: pointer of type
DB: The name of the database to be created
If the database was successfully created, zero is returned, and nonzero if an error occurs.

----------------------------------------------

Look again at the example:

Many people use MySQL to develop some projects, sometimes for performance, we will directly use the C language to develop relevant modules, especially in our web applications, although PHP, JSP and other scripts provide MySQL interface, but obviously directly using C language has better security and performance, Michael used to develop a number of projects in PHP using the C language of this type of interface, and then compiled into PHP, for the PHP script to use directly, this topic is not much to say, the following is mainly on Linux under the C language to connect the MySQL database, and read the inside of the How the data is returned, and how it is compiled.

Most of the code here refer to the. C source files in the MySQL release package, and you can also go inside to find the relevant code, the following code realizes the connection to the local MySQL server on the 9tmd_bbs_utf8 database, from the data table Tbb_ User obtains the user's username and prints the output to the terminal based on the UserID entered.

#ifDefined(_win32)||Defined(_win64)To support compilation on the Windows platform
#include<Windows.h>
#endif
#include<Stdio.h>
#include<Stdlib.h>
#include"Mysql.h"//On my machine this file is under/usr/local/include/mysql

A macro that defines a database operation, or you can leave it behind and write it directly into the code
#defineSelect_query"Select username from tbb_user where UserID =%d"

IntMain(intargc, Char**Argv)Char **argv equivalent to char *argv[]
{
MysqlMysql,*Sock;Defines a handle to a database connection, which is used for almost all MySQL functions
Mysql_res*Res;Query result set, struct type
Mysql_field*Fd;structure that contains field information
Mysql_rowRow;Array of strings that hold a row of query results
CharQbuf[160];Storing query SQL statement strings

If(argc!=2){Check input parameters
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",0Null,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 (a Rgv[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;   //. For compatibilityMost of the compilers join 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, depending on your environment

When running, execute the following command

./mysql_select 1

The following results are returned:

Number of fields Returned:1
ther userid #1 ' s username is:michael
Query OK!

The above code I think most can understand, do not understand can refer to MySQL provided in the C language API part of the document, each function is detailed, I have time to organize a common API description.

C-language operation MySQL Database

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.