[MySQL]——Common interface API, that is, related function descriptions

  

Table of contents

  

1. Description of MySQL structure

1. MYSQL structure

2.MYSQL_RES structure

3. MYSQL_FIELD 

2. Steps for using the interface

3. mysql_init()——MYSQL object initialization

 4. mysql_real_connect()——The database engine establishes a connection

5. mysql_query()——Query the contents of a certain table in the database 

6. mysql_real_query——Execute SQL statements

7. mysql_store_result() - Retrieve the complete result set from the client

8. mysql_fetch_row()——Get the next row from the result set

9. mysql_field_count()——Returns the number of columns in the table

10. mysql_fetch_fields()——to obtain the contents of the table header

11. Function prototype and parameter description

12. mysql_free_result() - Release the memory used by the result set

13. mysql_close()——Close the database connection


1. Description of MySQL structure

1. MYSQL structure


Before connecting to the database, you must first . This variable is used in many Mysql API functions. It contains some connection information and other data.创建MYSQL变量

typedef struct st_mysql {
NET  net;            /* Communication parameters 通讯参数,网络相关*/
unsigned char connector_fd;   /* ConnectorFd for SSL 加密套接字协议层*/

char  *host,*user,*passwd,*unix_socket,*server_version,
*host_info,*info,*db;//数据库用户名,密码,主机名,Unix套接字,版本,主机信息

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;

2.MYSQL_RES结构体

MYSQL_RES 结构体Contains  the query result set  , which is the data queried from the database. Can be obtained using mysql_store_resultthe or  mysql_use_result function. The definition is as follows:

typedef struct st_mysql_res {
  my_ulonglong  row_count;
  MYSQL_FIELD   *fields;
  MYSQL_DATA    *data;
  MYSQL_ROWS    *data_cursor;
  unsigned long *lengths;       /* column lengths of current row */
  MYSQL     *handle;        /* for unbuffered reads */
  const struct st_mysql_methods *methods;
  MYSQL_ROW row;            /* If unbuffered read */
  MYSQL_ROW current_row;        /* buffer to current row */
  MEM_ROOT  field_alloc;
  unsigned int  field_count, current_field;
  my_bool   eof;            /* Used by mysql_fetch_row */
  /* mysql_stmt_close() had to cancel this result */
  my_bool       unbuffered_fetch_cancelled;  
  void *extension;
} MYSQL_RES;

3. MYSQL_FIELD 

3. MYSQL_FIELD It contains information such as field name , field type and size . You can call the function repeatedly mysql_fetch_fieldto obtain information about all fields

typedef struct st_mysql_field {
  char *name;                 /* Name of column */
  char *org_name;             /* Original column name, if an alias */
  char *table;                /* Table of column if column was a field */
  char *org_table;            /* Org table name, if table was an alias */
  char *db;                   /* Database for table */
  char *catalog;	      /* Catalog for table */
  char *def;                  /* Default value (set by mysql_list_fields) */
  unsigned long length;       /* Width of column (create length) */
  unsigned long max_length;   /* Max width for selected set */
  unsigned int name_length;
  unsigned int org_name_length;
  unsigned int table_length;
  unsigned int org_table_length;
  unsigned int db_length;
  unsigned int catalog_length;
  unsigned int def_length;
  unsigned int flags;         /* Div flags */
  unsigned int decimals;      /* Number of decimals in field */
  unsigned int charsetnr;     /* Character set */
  enum enum_field_types type; /* Type of field. See mysql_com.h for types */
  void *extension;
} MYSQL_FIELD;

4. MYSQL_ROWThis is a type-safe representation of row data . Currently it is implemented as a string array counting bytes. (If the field values ​​may contain binary data, you cannot treat these as null-terminated strings, since such values ​​can contain null bytes internally.) Rows are obtained by calling mysql_fetch_row().

typedef char **MYSQL_ROW;

For example:

Get the first row of data from the result set, as follows:

|    1 | 孙悟空    | 2022-04-26 17:02:54 | NULL | NULL   
MYSQL_ROW row = mysql_fetch_row(result));
则row中存储的是: 
" “1” "孙悟空"  “2022-04-26 17:02:54” "NULL" "NULL""

2. Steps for using the interface

1、首先要包含mysql的头文件,并链接mysql动态库。

#include <mysql.h>

//创建MYSQL对象句柄
MYSQL* m_mysql=new mysql;
mysql_init(&m_mysql);

//或者
MYSQL* m_mysql=mysql_init(&NULL);

//连接
mysql_real_connect()

//查询数据
const char * query = "select * from student";
ret = mysql_query(connect, query);
if(ret != 0){
     printf("mysql_query error\n");
     return ret;
}

//获取查询的结果集
 MYSQL_RES *result = mysql_store_result(&mysql);
if(result == NULL){
     printf("mysql_store_result error\n");
     return -1;
}

//获取查询的行数
int field_num = mysql_field_count(&mysql);
//获取表头数据
MYSQL_FIELD * fields = mysql_fetch_fields(result);


//获取每一行的数据
 MYSQL_ROW row = NULL;
 while(row = mysql_fetch_row(result)){
      for(i= 0; i < field_num; i++){
            printf("%s \t", row[i]); 
      }
      printf("\n");
 }


 mysql_free_result(result);//释放内存
 mysql_close(connect);//关闭连接

3. mysql_init()——MYSQL object initialization

Function prototype and parameter description

Allocate or initialize  a MYSQL object appropriate to mysql_real_connect ()

MYSQL *mysql_init(MYSQL *mysql) 

return value: 

  • Initialized MYSQL* handle. If there is not enough memory to allocate the new object, NULL is returned. Error, in case of insufficient memory, returns NULL.

parameter:

  • If mysql is a NULL pointer, this function will allocate, initialize, and return the new object.

  • Otherwise, the object is initialized and the object's address is returned.

  • If mysql_init () allocates a new object, mysql_close () should be called in the program to close the connection to release the object

 4. mysql_real_connect()——The database engine establishes a connection

Function:
Connect to the database engine and try to establish a connection with the MySQL database engine running on the host through the function mysql_real_connect ().

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 long client_flag) 

return value: 

  • If the connection is successful, the MYSQL* connection handle is returned.
  • If the connection fails, NULL is returned. For a successful connection, the return value is the same as the value of the first parameter.

Parameter Description:

  • mysql: MYSQL variable defined previously;
  • host: The address of the MYSQL server; if "host" is NULL or the string "localhost ", the connection will be treated as a connection to the local host. If the operating system supports sockets (Unix) or named pipes (Windows), they will be used instead of TCP/IP to connect to the server.
  • user: Login user name ; if "u ser" is NULL or the empty string "", the user will be regarded as the current user. In a UNIX environment, this is the current login name.
  • passwd: login password ;
  • db: The name of the database to be connected. If db is NULL, the connection will set the default database to this value.
  • port: TCP service port of the MYSQL server ; if "port" is not 0, its value will be used as the port number of the TCP/IP connection. Note that the "host" parameter determines the type of connection.
  • unix_socket: unix connection method. If unix_socket is not NULL, this string describes the socket or named pipe that should be used. Note that the "host" parameter determines the type of connection.
  • clientflag: Mysql runs as a flag for the ODBC database, usually 0

5. mysql_query()——Query the contents of a certain table in the database 

4.1. Function prototype and parameter description

Query the contents of a table in the database through the function mysql_query().

int mysql_query(MYSQL *mysql, const char *query) 
//query为执行的SQL语句对应的字符长串
  • Execute the SQL query pointed to by the "Null-terminated string " query.
  • Under normal circumstances, the string must contain 1 SQL statement , and no terminating semicolon (';') or "\g" should be added to the statement. If multiple statement execution is allowed, the string can contain multiple statements separated by semicolons. ("C API Handling of Multiple Query Executions")
  • mysql_query() cannot be used for queries containing binary data , and mysql_real_query()  should be used instead (binary data may contain the character '\0', which mysql_query() will interpret as the end of the query string).
  • If you want to know whether the query should return a result set, you can use mysql_field_count () to check.

6. mysql_real_query——Execute SQL statements

int mysql_real_query(MYSQL *mysql, const char *query, unsigned int length)
  •  mysql: MYSQL variable defined previously;
  • query:sql statement string
  • length: The length of the query string, excluding \0;

illustrate:

For queries that contain binary data , you must use mysql_real_query() instead of mysql_query() because the binary code data may contain "\0" characters. Also, mysql_real_query() is faster  than mysql_query() because it is called on the query string. strlen().

return value:

Zero if the query is successful . Nonzero if an error occurred.

7. mysql_store_result() - Retrieve the complete result set from the client


Function prototype and parameter description
Display the contents of the data table in the query database. mysql_store_result () reads all the results of the mysql_query() query to the client, allocates a MYSQL_RES structure (described above), and places the results in the structure.

MYSQL_RES *mysql_store_result(MYSQL *mysql) 

return value

A result collection with multiple results MYSQL_RES. If an error occurs, NULL is returned.

  • For every query ( SELECT, SHOW, DESCRIBE, EXPLAIN, CHECK TABLE, etc.) that successfully retrieves data , mysql_store_result() or mysql_use_result() must be called.
  • If you want to know whether the query should return a result set, you can use mysql_field_count () to check.
  • If the query does not return a result set , mysql_store_result() will return a Null pointer (for example, if the query is an INSERT statement).
  • If reading the result set fails , mysql_store_result () will also return a Null pointer. You can check whether an error occurred by checking whether mysql_error () returns a non-empty string, whether mysql_errno() returns a non-zero value, or whether mysql_field_count() returns 0.
  • If no rows are returned, an empty result set is returned. (The empty result set setting is different from the null pointer that is the return value).
  • Once you have called mysql_store_result () and obtained a result that is not a Null pointer, you can call mysql_num_rows () to find out the number of rows in the result set.
  • You can call mysql_fetch_row () to get a row in the result set , or call mysql_row_seek () and mysql_row_tell() to get or set the current row position in the result set.
  • Once you have finished operating on the result set, you must call mysql_free_result()
     

8. mysql_fetch_row()——Get the next row from the result set

MYSQL_ROW mysql_fetch_row(MYSQL_RES* result)
//MYSQL_ROW开篇已经说明,char ** 类型
  • The structure of the next line MYSQL_ROW. If 没有there are more rows to retrieve or an error occurred, NULL is returned.
  • When used after mysql_store_result (), mysql_fetch_row () returns NULL if there are no rows to retrieve .
  • When used after mysql_use_result (), mysql_fetch_row() returns NULL if there are no rows to retrieve or an error occurs.
  • The number of values ​​in the row is given by  mysql_num_fields(result)  . If the value returned by calling mysql_fetch_row () is stored in the row  , the pointers to these values ​​will be accessed from  row[0] to row[mysql_num_fields(result)-1] .
  • The lengths of field values ​​in a row can be obtained by calling mysql_fetch_lengths()  . For empty fields and fields containing NULL, the length is 0. You can distinguish between field values ​​by examining their pointers. If the pointer is NULL, the field is NULL, otherwise the field is empty
     

9. mysql_field_count()——Returns the number of columns in the table

Returns the number of columns of the most recent query applied to the join.

unsigned int mysql_field_count(MYSQL *mysql) 


return value

An unsigned integer representing the number of columns in the result set.
Instructions for use:
The normal use of this function is when  mysql_store_result()  returns NULL (therefore no result set pointer) . In this case, mysql_field_count() can be called to determine whether mysql_store_result() should produce a non-null result . This way, the client can take appropriate action without knowing whether the query is a SELECT (or SELECT-like) statement .


10. mysql_fetch_fields()——to obtain the contents of the table header

For a result set,  MYSQL_FIELD an array of all structures is returned. Each structure provides a field definition for one column in the result set.

MYSQL_FIELD *mysql_fetch_fields(MYSQL_RES *result) 
//MYSQL_FIELD 开篇已经说明

return value

  • MYSQL_FIELDArray of structures about all columns of the result set .

11. Function prototype and parameter description


Call mysql_use_result to initialize the retrieval so that the result set can be read row by row without itself reading any data from the server. This method is faster and requires less memory than the first method, but it will bind Define the server to prevent other threads from updating any tables, and mysql_fetch_row must be executed repeatedly to read data until NULL is returned. Otherwise, the unread rows will be returned as part of the result in the next query, so we often use mysql_store_result
 

MYSQL_RES *  mysql_use_result(MYSQL *mysql);

12. mysql_free_result() - Release the memory used by the result set

Releases the memory allocated by mysql_store_result(), mysql_use_result(), etc. for the result set. mysql_list_dbs()After completing the operation on the result set, you must call to mysql_free_result()release the memory used by the result set.

void mysql_free_result(MYSQL_RES *result) 

13. mysql_close()——Close the database connection

Close the previously opened connection. The connection handle pointed to by mysql will also be deallocated if the handle was automatically allocated by mysql_init()or .mysql_connect()mysql_close()

void mysql_close(MYSQL *mysql) 

Guess you like

Origin blog.csdn.net/sjp11/article/details/132085550