编程知识 cdmana.com

MySQL learning - C API

 C API Provide right MySQL client / The server Low level access , bring C Programs can access MySQL What's in the database .C API The code is and MySQL Released together , And in libmysqlclient Library to implement . May refer to 27.8.1 section MySQL C API Realization . Most clients API Use libmysqlclient Library and MySQL The server communicates (Connector/J Connector/Net With the exception of ). It means , You can use the same environment variables with other client programs , Because they are all libmysqlclient References to . Can be found in 4.1 section MySQL Get a list of these variables in the Overview .

        of C API Instructions for building client programs can be found in 27.8.4.1 Section construction C API Client program . About multithreading programming , You can see 27.8.4.3 be based on C API Write multithreaded client program . To create a stand-alone application that contains the server client in the unified program ( Not with the outside MySQL Server communication ), May refer to 27.7 section libmysqld, The embedded MySQL Server Library .

Be careful :

        If after the upgrade , Encountered a problem with the compiled client program , For example, commands are out of sync or unexpect core dumps, This program may be compiled with the old version of the header file and library file . under these circumstances , You need to check the mysql.h and libmysqlclient.a The date of the library , To verify if it's from the new MySQL Distribution version . If not , Please recompile the program with the latest header files and Libraries . If the version number of the library changes ( For example, from libmysqlcilet.so.17 To libmysqlcilet.so.18), Programs that use shared libraries also need to be recompiled , Other Jianrong information , For reference. 27.8.4.4 section function C API Client program .

    The client has the largest communication buffer , The initial allocated buffer size is 16KB Will automatically increase to the maximum 16MB. Because the buffer size is only increased when the demand is guaranteed , So simply increasing the maximum limit itself will not use more resources . This size check is mainly aimed at the prevention of error statements and communication packets .

    The communication buffer must be large enough , To include a single SQL sentence ( be used for client To server Of data traffic ) And a row to return data (server To client Of data traffic ). The communication buffer for each callback is dynamically enlarged , To process any query up to the maximum limit . for example , If your BL0B Value inclusion 16MB data , Must have at least 16MB Communication buffer limit for (server,client There must be ). The maximum default value built into the client is 1GB, But the default maximum value in the server is 1MB. You can change it when the server starts max_allowed_packet Parameter to increase this value . Details available 5.1.1 Section configuration server .

        After each query MySQL The server shrinks each communication buffer to net_buffer_length Bytes , For clients , Before the link is closed , The size of the buffer associated with the link does not decrease , When the link is closed , The client is responsible for reclaiming memory .

C API data structure

    This section describes the C API data structure . For information on preprocessing, refer to 27.8.9 section "C API Preprocessing data structure "
  • MYSQL : This structure represents a handle to a database link . This structure is used for almost all MySQL function . Do not attempt to copy this structure ,MySQL This structure is not guaranteed to be available after replication
  • MYSQL_RES:    This structure represents the return of query results in units of behavior (SELECT,SHOW,DESCRIBE,EXPLAIN). The information returned by the query is In the following chapters The result set .
  • MYSQL_ROW: This is a type safe representation of a row of data . It is currently implemented as a string array in byte Technology ( If the field contains binary data , They cannot be regarded as null a null-terminated string , Therefore, such values may contain internally null byte .). Usually by calling mysql_fetch_row() Get row data .
  • MYSQL_FIELD: This structure contains metadata information (metadata): About field information , Field name , Type and size, etc . Other members of this structure are described in detail later . You can call it repeatedly mysql_fetch_field() For each field MYSQL_FIELD structure . The field value is not part of this structure , They are included in MYSQL_ROW In structure .
  • MYSQL_FIELD_OFFSET: This is a MySQL Type safe representation of offset in field list .mysql_field_seek() Function USES MYSQL_FIELD_OFFSET. The offset is the field number in a row , from 0 Start .
  • my_ulonglong: This type is used for mysql_affected_rows(),mysql_num_rows() as well as mysql_insert_id() The number of multiple corresponding rows , The range of values of this type is 0---1.84e19. some The return value type is this type Function using return -1, To indicate an error or exception . You can use the ((my_ulonglong) -1 perhaps (my_ulonglong) ~0) Compare to detect -1 The situation of . Try printing on some systems my_ulonglong The value of type is invalid , The value of this type to print , It can be converted to unsigned long long And use %lu Print :
    printf ("Number of rows: %lu\n",(unsigned long) mysql_num_rows(result));
  • my_bool:bool Type is used to represent true and false
    MYSQL_FIELD Structure contains the members described in the following list . These definitions apply primarily to the columns of the result set , for example SELECT Statement generated column .MYSQL_FEILD Structure is also used to call the returned OUT And the incoming INOUT Parameters provide metadata .
typedef struct st_mysql_field {
  char *name;                 /*  Column name  */
  char *org_name;             /*  If there are aliases, ignore aliases , Is the original column name */
  char *table;                /* ( Non computational ) The name of the table for the field . If it is a calculated field , Is an empty string  */
  char *org_table;            /*  If table If it's an alias ,org_table Is the original table name  */
  char *db;                   /*  Database name  */
  char *catalog;	      /*  Table directory , Always be "def" field value  */
  char *def;                  /*  Field defaults ( Use mysql_list_fields() Set up ) */
  unsigned long length;       /*  Column width , In bytes  */
  unsigned long max_length;   /*  The maximum width of the selected collection  */
  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;         /*  Field bit flag  */
  unsigned int decimals;      /*  Decimal places in field  */
  unsigned int charsetnr;     /*  Character set  */
  enum enum_field_types type; /*  Field type  */
  void *extension;
} MYSQL_FIELD;


C API Function Overview

  Here's a summary of the list C API Some common functions in , More details can be referred to 27.8.7 C API Function description .
  • my_init(): Initializing global variables and thread handlers in thread safe programs
    MYSQL *mysql_init(MYSQL *mysql);
    /* describe :
         To apply to mysql_real_connect() Of MYSQL Object allocates memory or initializes MYSQL object . If mysql==NULL, This function creates a MYSQL* Object and allocate memory , Returns the address of the object after initialization . If mysql_init() Assign a new object , In the call mysql_close() Release the object when the connection is closed 
         In the case of non multithreading ,mysql_init() It will be called automatically as needed mysql_library_init(). but mysql_library_init() It's not thread safe , therefore mysql_init() It's also non thread safe . Calling mysql_init() Before , Or call before generating any thread. mysql_library_init() Either use mutex to protect mysql_library_init() Call to . This should be done before the client calls the client library .
     Return value :
         Initialized MYSQL* object , If there is not enough memory , Then return to NULL
     error :
         If there is not enough memory , return NULL
    */

    mysql_affected_rows(): Return to last UPDATE,DELETE,INSERT Number of rows affected in .

    my_ulonglong mysql_affected_rows(MYSQL *mysql);
    /*
     describe :
         In the use of mysql_query() perhaps mysql_real_query() perform MySQL After the statement , Can call immediately mysql_affected_rows(). If the last statement is UPDATE,DELETE,INSERT, Then it returns the line number affected by the execution of the statement . about SELECT Come on ,mysql_affected_rows() Working mode and mysql_num_rows() similar .
         about UPDATE sentence , By default, the affected line number is the actual modified line number , If you are connecting to mysqld When it comes to mysql_real_connect() Of CLIENT_FOUND_ROWS sign , The affected row value is the number of rows found . That is, by WHERE Clause match .
         about REPLACE sentence , If the new row replaces the old one , be affected-rows The value is 2, Because in this case, after deleting the old line, another line is inserted .
         about INSERT...ON DUPLICATE KEY UPDATE sentence , If a new row is inserted, the affected value is 1, If you update an existing row, the affected row value is 2. If you set an existing row as the current row, the affected value is 0. If you specify CLIENT_FOUND_ROWS sign , If you set an existing row to the current value, the affected row value is 1 No 0.
         In the stored procedure's CALL After statement ,mysql_affected_rows() Returns the value returned by executing the last statement in a stored procedure , If the last statement returns -1, be mysql_affected_rows() return 0. In the process , You can SQL Level use ROW_COUNT() To get the row values affected by each statement .
         stay MySQL5.7 in ,mysql_affected_rows() Return meaningful values for a broader statement .
     Return value :
        >0: Represents the number of rows affected or retrieved 
        =0: Not for UPDATE Statement update record , Not associated with WHERE Clause matches or no query has been executed 
        -1: Indicates that the query returned an error . Or for SELECT, Calling mysql_store_result() It was called before mysql_affected_rows()
         because mysql_affected_rows() Returns an unsigned value , So you can use the (my_ulonglong)-1 perhaps (my_ulonglong)~0 To check -1 The situation of 
     error :
    */
    // Example :
    char *stmt = "UPDATE products SET cost=cost*1.25 WHERE group=10";
    mysql_query(&mysql,stmt);
    printf("%ld products updated",(long) mysql_affected_rows(&mysql));

     

  • mysql_autocommit(): Turn auto submit mode on or off
  • mysql_change_user(): Change users and databases on open links
  • mysql_character_set_name(): Returns the default character set name of the current link
  • mysql_client_find_plugin(): Returns the plug-in pointer
  • mysql_client_register_plugin(): Register plug-ins
  • mysql_close(): Close server link
  • mysql_commit(): Submit things
  • mysql_connect(): link MySQL The server , This feature is not recommended , Please amend it to mysql_real_connect()
  • mysql_create_db(): Create a database , This feature is not recommended , Please switch to SQL sentence CRETE DATEBASE
  • mysql_data_seek(): Find any line number in the query result set .
  • mysql_debug(): With the given string DBUG_PUSH
  • mysql_drop_db(): Delete database , It is not recommended to use , Please amend it to SQL sentence ,DROP DATABASE
  • mysql_dump_debug_info(): Causes the server to write debug information to the log
  • mysql_eof(): Determine if the last row of the result set has been read , This function is not recommended , Please switch to mysql_errno() perhaps mysql_error()
  • mysql_errno(): Returns the most recently called MySQL The error number of the function
  • mysql_error(): Returns the most recently called MySQL Error message for function
    const char *mysql_error(MYSQL *mysql);
    /*
     describe :
        about mysql Specified link ,mysql_error() Return one to null a null-terminated string , Which contains the most recently called API Error message for function , If the function does not fail , be mysql_error() The return value of may be a previous error or an empty string indicating no error . As a rule of thumb, all functions that must ask the server for information are reset if they succeed mysql_error(). For reset mysql_error() Function of , You can use either of the following two tests to check for errors :
       if(*mysql_error(&mysql))
    {
      // an error occurred
    }
    if(mysql_error(&mysql)[0])
    {
      // an error occurred
    }
     This can be done by MySQL Client library to change the language of client error messages . You can choose error messages in many different languages .
     Return value : With null The ending string describing the error message . If there are no mistakes , Returns an empty string 
     error : nothing 
    */

    

  • mysql_escape_string(): Escape special characters in a string for SQL sentence
  • mysql_fetch_field(): Returns the next table field type
    MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result);
    /*
     describe :
         Define a column of data in the result set as MYSQL_FIELD Structure returns . Call this function repeatedly to retrieve information about all the columns in the result set . When there are no fields left ,mysql_fetch_filed() return NULL. Every time a new SELECT When inquiring ,mysql_fetch_field() Is reset to return information about the first field .mysql_fetch_field() The returned fields are also affected mysql_field_seek() Influence .
         If you call mysql_query() To execute on the table SELECT Operation, but no call mysql_store_result(). So if you call mysql_fetch_field() Will ask BLOB Length of field ,MySQL The default will be returned blob length (8KB).( choice 8KB The size is because MySQL I do not know! BLOB Maximum length of . This should be configurable .) Once the retrieval returns the result set ,field->max_length Contains the length of the maximum value in the column .
     Return value :
         Returns the current value of the result set MYSQL_FIELD structure , Returns if there is no current column NULL
     error : nothing 
    */
    // Example 
    MYSQL_FIELD *field;
    while((field = mysql_fetch_field(result)))
    {
        printf("field name %s\n", field->name);
    }
     
  • mysql_fetch_filed_direct(): Give a field number , Returns the type of the table field
  • mysql_fetch_fileds(): Returns an array of all field results .
  • mysql_fetch_lengths(): Returns the length of all columns in the current row
    unsigned long *mysql_fetch_lengths(MYSQL_RES *result);
    /*
     describe :
         Returns the column width of the current row in the result set . If you plan to copy field values , This length information is useful for optimization , Because after using this function , You can avoid calling strlen() function . In addition, if the result set contains binary data , You must use this function to determine the data size , because strlen Will end at a null character so that it returns an incorrect field width . Empty column or contain NULL The length of the value column returned is 0.
     Return value :
         An unsigned long integer array that represents the size of each column ( Does not include any terminating null bytes ), Return if an error occurs NULL
     error :
        mysql_fetch_lengths() Valid only for the current row of the result set , If you're calling mysql_fetch_row() It will be returned before or after all rows in the retrieval result NULL.
    */
    // Example :
    MYSQL_ROW row;
    unsigned long *lengths;
    unsigned int num_fields;
    unsigned int i;
    row = mysql_fetch_row(result);
    if (row)
    {
        num_fields = mysql_num_fields(result);
        lengths = mysql_fetch_lengths(result);
        for(i = 0; i < num_fields; i++)
        {
             printf("Column %u is %lu bytes in length.\n",i, lengths[i]);
        }
    }
  • mysql_fetch_row(): Get the next line from the result set
    MYSQL_ROW mysql_fetch_row(MYSQL_RES *result);
    /*
     describe :
        mysql_fetch_row() Retrieve the next row of data in the result set . When using mysql_store_result() or mysql_use_result() after , If there are no remaining rows in the result set or an error occurs mysql_fetch_row() return NULL. The number of values in a data row is determined by mysql_num_fields() give . If row Save the mysql_fetch_row() The value returned , Then the accessible value range is row[0]--row[mysql_num_fields(result)-1]; That is, the number of data in a row is mysql_num_fields(result) The return value of .NULL The pointer represents the NULL value .
         You can use mysql_fetch_lengths() To get the length of the field value in the row . Empty fields and contains NUL The length of all the fields is 0; You can distinguish by checking the pointer to the field value . If the pointer is NULL, Then the field is NULL. Otherwise, the field is empty 
     Return value :
         Of the next row of data MYSQL_ROW structure . or NULL.NULL The meaning of return depends on mysql_fetch_row() Functions previously called . stay mysql_store_result() or mysql_use_result() Then call , If there are no rows to retrieve or an error occurs mysql_fetch_row() return NULL. To determine if an error has occurred , Please check mysql_error() Is an empty string or mysql_errno() Return non 0 value .
     error :
         call mysql_fetch_row() Errors will not be reset .
        CR_SERVER_LOST: Disconnect from server during query 
        CR_UNKNOWN_ERROR: Unknown error 
    */
    // Example :
    MYSQL_ROW row;
    unsigned int num_fields;
    unsigned int i;
    num_fields = mysql_num_fields(result);
    while ((row = mysql_fetch_row(result)))
    {
       unsigned long *lengths;
       lengths = mysql_fetch_lengths(result);
       for(i = 0; i < num_fields; i++)
       {
           printf("[%.*s] ", (int) lengths[i],
                  row[i] ? row[i] : "NULL");
       }
       printf("\n");
    }
  • mysql_field_count(): Returns the number of result columns for the most recent statement
    unsigned int mysql_field_count(MYSQL *mysql);
    /*
     describe :
         Returns the number of columns in the latest query result set . Normal use of this function is in the mysql_store_result() return NULL when . under these circumstances , You can call mysql_field_count() To make sure mysql_store_result() Generate non empty result . This enables the client program to not know whether the query is SELECT Or similar SELECT Statement to take appropriate action .
         Another way is to use mysql_errno(…&mysql) To replace mysql_field_count(&mysql). under these circumstances , You check directly mysql_store_result() Mistakes in , Not from mysql_field_count() To infer whether the statement is SELECT.
     Return value : Signed integer number , The number of columns in the result set 
     error :
    */
    // Example 
    MYSQL_RES *result;
    unsigned int num_fields;
    unsigned int num_rows;
    
    if (mysql_query(&mysql,query_string))
    {
        // error
    }
    else // query succeeded, process any data returned by it
    {
        result = mysql_store_result(&mysql);
        if (result)  // there are rows
        {
            num_fields = mysql_num_fields(result);
            // retrieve rows, then call mysql_free_result(result)
        }
        else  // mysql_store_result() returned nothing; should it have?
        {
            if(mysql_field_count(&mysql) == 0)
            {
                // query does not return data
                // (it was not a SELECT)
                num_rows = mysql_affected_rows(&mysql);
            }
            else // mysql_store_result() should have returned data
            {
                fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
            }
        }
    }
  • mysql_field_seek(): Place the column cursor over the specified column
  • mysql_field_tell(): Return for the last mysql_fetch_field() The cursor position of the field
  • mysql_free_result(): Release the memory used by the result set
  • mysql_get_character_set_info(): Returns information about the default string set
  • mysql_get_client_info(): Returns the version information of the client as a string
  • mysql_get_client_version(): Returns the client version information as an integer
  • mysql_get_host_info(): Returns a string describing the link .
  • mysql_get_option(): return mysql_options() The value of the option
  • mysql_get_proto_info(): Returns the version of the protocol used by the link
  • mysql_get_server_info(): Returns the server version number
  • mysql_get_server_version(): Returns the server version number as an integer .
  • mysql_get_ssl_cipher(): Returns the current SSL password
  • mysql_hex_string(): Encode a string in hexadecimal format
  • mysql_info(): Returns information about the most recently executed query
  • mysql_init(): Gets or initializes MYSQL structure .
  • mysql_insert_id(): Returns the previous query as AUTO_INCREMENT Column generated ID.
  • mysql_kill(): Kill the specified process
  • mysql_library_end(): complete MySQL C API library
  • mysql_library_init(): initialization MySQL C API library
  • mysql_list_dbs(): Returns the database name that matches a simple regular expression
  • mysql_list_fields(): Returns the field name that matches the simple regular expression
  • mysql_list_processes(): Returns the current server thread list
  • mysql_list_tables(): Returns the table name that matches a simple regular expression
  • mysql_load_plugin(): Loading a plug-in
  • mysql_load_plugin_v(): Add plug-ins
  • mysql_more_result(): Check for more results
  • mysql_next_result(): return / Start the next result of multiple result execution
  • mysql_num_fields(): Returns the number of columns in the result set
    unsigned int mysql_num_fields(MYSQL_RES *result);
    /*
     To pass MYSQL* Parameters use unsigned int mysql_field_count(MYSQL* mysql)
     describe :
         Returns the number of columns in the result set . You can start with a pointer to the result set (MYSQL_RES *) or (MYSQL*) Get result set columns . If mysql_store_result() or mysql_use_result() return NULL( There is no result set pointer ), You can call mysql_field_count() To make sure mysql_store_result() Whether to generate non empty result set . This enables the client program to not know whether the query is SELECT( Or similar SELECT) Statement to take appropriate action . The example here illustrates the following operation :
     Return value :
         Represents the number of columns in the result set , It's an unsigned integer 
     error :
         nothing 
    */
    // Example :
    MYSQL_RES *result;
    unsigned int num_fields;
    unsigned int num_rows;
    if (mysql_query(&mysql,query_string)){
        // error
    }else {
        // query succeeded, process any data returned by it
        result = mysql_store_result(&mysql);
        if (result){
            // there are rows
            num_fields = mysql_num_fields(result);
            // retrieve rows, then call mysql_free_result(result)
        }else {
            // mysql_store_result() returned nothing; should it have?
            if (mysql_errno(&mysql))
            {
               fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
            }else if (mysql_field_countmysql_field_count(&mysql) == 0)
            {
                // query does not return data
                // (it was not a SELECT)
                num_rows = mysql_affected_rows(&mysql);
            }
        }
    }
  • mysql_num_rows(): Returns the number of rows in the result set
    my_ulonglong mysql_num_rows(MYSQL_RES *result);
    /*
     describe :
         Returns the function in the result set .mysql_num_rows() It depends on how you use it mysql_store_result() still mysql_next_result() To return the . If you are using mysql_store_result() Can be called immediately mysql_num_rows() To get the number of rows in the result set . If you are using mysql_use_result(), Before all rows in the result set are retrieved ,mysql_num_rows() It will not return the correct value .mysql_num_rows() A statement designed to return a result set, such as SELECT. about INSERT,UPDATE,DELETE Such statements , have access to mysql_affected_rows() To get the number of rows affected .
     Return value : Return the number of rows in the result set 
     error : nothing 
    */
  • MYSQL_RES *mysql_store_result(MYSQL *mysql)(): by mysql_real_connect() Set link options .
  • mysql_options4(): by mysql_real_connect() Set link options
  • mysql_ping(): Check if the link to the server is normal , Reconnection if necessary
  • mysql_plugin_options(): Set a plug-in option
  • mysql_query(): Execute one SQL Inquire about
    int mysql_query(MYSQL *mysql, const char *stmt_str);
    /*
     describe :
         Execute to null At the end of the SQL Statement string stmt_str. Usually a string must be a single string MySQL sentence , Without terminating semicolon “;”. If multi statement execution is enabled , The string can contain multiple statements separated by semicolons .mysql_query() Cannot be used for statements containing binary data , If the data contains binary data, you must use mysql_real_query(). If you want to know if the statement returns a result set , have access to mysql_field_count() To check .
     Return value :
         Execution successful return 0, Execution failure returns a negative number .
     error :
        CR_COMMANDS_OUT_OF_SYNC: The command was executed in an incorrect order 
        CR_SERVER_GNOME_ERROR:MySQL  The server has been lost 
        CR_SERVER_LOST: The link to the server is broken during the query 
        CR_UNKNOWN_ERROR: Unknown error 
    */
  • mysql_real_connect(): link MySQL The server
    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);
    /*
     describe :
       mysql_real_connect() An attempt was made to connect to the MySQL Database engine .mysql_real_connect() You must run successfully before you can perform other needs MYSQL Structural API function .
     Parameters :
        mysql: Use by mysql_init Initialized MYSQL structure . You can use mysql_options() Call to change many other link options .
        host: It can be the host name or IP Address .
             host=NULL perhaps host=localhost, It is assumed that it is connected to the local host , stay windows On if server Shared memory connection used , The client uses shared memory and server Link ; stay Unix Use on client socket Link ,unix_socket Parameters or MYSQL_UNIX_PORT Environment variables can be used to specify socket name . stay windows On if host="." Or not enabled TCP/IP And no unix_socket perhaps host=NULL, If server Named pipe enabled , Then the client uses the famous pipeline to link ; If server Named pipes are not enabled , Then something goes wrong , Otherwise, an error occurs .
              Can be set by MYSQL_OPT_PROTOCOL perhaps MYSQL_OPT_NAME_PIPE Option to determine the type of link to use , But the premise is server These link types must be supported .
        user: Is the user logged in MySQL Username , If user Is an empty string or NULL, The current user is assumed to be used , stay unix The current user is the login name of the current login system , stay windows ODBC Next , The specified current user name must be displayed .
      passwd: Sign in MySQL The user password of . If passwd=NULL, Then check whether the users with empty password field in the user table match . This enables the database administrator to set up MySQL Authority system , That is, users can get different permissions according to whether they have specified a password .
               Be careful : Calling mysql_real_connect() Before , Don't try to encrypt the password , Password encryption is performed by the client API Automatically .
              user and passwd Use as MYSQL Any character set configured . By default latin1 Character set , But it can be called before connecting. mysql_options(mysql,MYSQL_SET_CHARSET_NAME,"charset_name") To change the .
          db: Database name , If db Not for NULL, The connection sets the default database to db Database represented .
          port: If port Not for 0, Then the value will be used as TCP/IP The port number of the connection , It should be noted that host Parameter determines the type of connection .
    unix_socket: If unix_socket Not for NULL, The string specified to be used socket Or named pipe , It should be noted that host Parameter determines the connection type 
    client_flag: Usually it is 0, But you can set a combination of the following flags to enable some features .
                CAN_HANDLE_EXPIRED_PASSWORDS: The client can handle expired passwords 
                CLIENT_COMPRESS: On the client side / Using compression in server protocol 
                CLIENT_FOUND_ROWS: Return to find matching function , Instead of the number of rows that have changed 
                CLIENT_IGNORE_SIGPIPE: Client organization library installation SIGPIPE Signal processing program , Can be used to avoid handler conflicts with installed applications 
                CLIENT_IGNORE_SPACE: Spaces after function names are allowed ,
                CLIENT_INTERACTIVE: Before closing the connection , allow interactive_timeout Seconds inactive , Client session in wait_timeout Variable to the session's interactive_timeout The value of the variable .
                CLIETN_LOCAL_FILLES: Enable LOAD DATA LOCAL Handle 
                CLIENT_MULTI_RESULTS: Tell the server if enabled , The client can process multiple result sets from multiple statement execution or stored procedures . If enabled CLIENT_MULTI_STATEMENTS Is automatically enabled CLIENT_MULTI_RESULTS.
                CLIENT_MULTI_STATEMENTS: Inform server , The client can use the ";" Send multiple statements separately . If this flag is not set , Multiple statement execution is disabled .
                CLIENT_NO_SCHEMA: Don't allow db_name,tbl_name,col_name grammar . This is aimed at ODBC Of . If you use this syntax, it may cause the parser to generate errors , For capture ODBC Program errors are useful .
                CLIENT_ODBC: It's useless 
                CILENT_SSL: Use SSL Cryptographic protocol , Do not set this option in the application . It is set inside the client library . Instead, call mysql_real_connect() Before using mysql_options() or mysql_ssl_set().
                CLIENT_REMEMBER_OPTIONS: Remember to call mysql_options() Specified options . Without this option , If mysql_real_connect() Failure , Must be called repeatedly before attempting to connect again mysql_options() With this option, you do not have to call repeatedly mysql_options.
                 If the program uses CALL Statement execution stored procedure , Must be enabled CLIENT_MULTI_RESULTS sign . This is because, in addition to any result set that the statement executed in the procedure might return , Every CALL Returns a result indicating the call status . because CALL Multiple results can be returned , So loop call mysql_next_result() To determine if there are more results .
                 call mysql_real_connect() When enabled CLIENT_MULTI_RESULTS You can pass it on CLIENT_MULTI_RESULTS Flag display call , It can also deliver CLIENT_MULTI_STATEMENTS To implicitly call . stay MySQL5.7 The default is to enable CLIENT_MULTI_RESULTS.
                 If enabled CLIENT_MULTI_STATMENTS or CLIENT_MULTI_RESULTS, Can be called through the loop mysql_next_result() To handle each call mysql_query() perhaps mysql_real_query() Result , To determine if there are more results .
                 For some parameters , You can get values from the options file , Without having to mysql_real_connect() The value passed in the display call of . To do this, call mysql_real_connect() Before using MYSQL_READ_DEFAULT_FILE perhaps MYSQL_READ_DEFAULT_GROUP Option call mysql_options. And then call mysql_readl_connect() Set when “no-value” The parameter to read the value from the options file .
                host: Appoint NULL Or empty string “”
                user: Appoint NULL Or empty string “”
                passwd: Appoint NULL, For passwords ,mysql_real_connect() The value of an empty string in the call cannot be overridden in the options file , Because empty strings explicitly indicate MySQL Account has empty password 
                db: Appoint NULL Or empty string “”
                port: Appoint 0
                unix_socket: Appoint NULL
                 If no value is found in the options file for the parameter , The default value is used .
     Return value :
         If the connection is successful , return MYSQL* Structure pointer , That is with mysql Parameters . Return if connection fails NULL.
     error :   
        CR_CONN_HOST_ERROR: Connect to MySQL Server failed 
        CR_CONNECTION_ERROR: Connect to local MySQL Server failed 
        CR_IPSOCK_ERROR: establish IP socket Failure 
        CR_OUT_OF_MEMORY: Out of memory 
        CR_SOCKET_CREATE_ERROR: establish Unix socket Failure 
        CR_UNKNOWN_HOST: Cannot find the corresponding host name IP Address 
        CR_VERSION_ERROR: Trying to connect to the server using a client with a different protocol version resulted in a protocol mismatch 
        CR_NAMEDPIPEOPEN_ERROR: stay windows Failed to create named pipe on 
        CR_NAMEDPIPEWAIT_ERROR: stay windows Failed to wait for a named pipeline on 
        CR_NAMEDPIPESTATE_ERROR: stay windows Failed to get the named pipe handle on 
        CR_SERVER_LOST: If connect_timeout>0 And it took more time to connect to the server than connect_timeout second , Or perform init_command Server crash .
        CR_ALREADY_CONNECTED:MYSQL The result pointer is already connected to the MySQL The server 
                  
    */
    MYSQL mysql;
    mysql_init(&mysql);
    mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"your_prog_name");
    if (!mysql_real_connect(&mysql,"host","user","passwd","database",0,NULL,0))
    {
        fprintf(stderr, "Failed to connect to database: Error: %s\n",
              mysql_error(&mysql));
    }
    /* By using mysql_options(),MySQL Client library read my.cnf In the document [client] and [your_prog_name] part , Make sure the program works properly . After connection ,mysql_real_connect() Before 5.0.3 Of API Reconnects the version flag (MYSQL Part of the structure ) Set to 1, In later versions, this flag is set to 0. This reconnection flag is 1 If the connection is lost and cannot be executed MySQL sentence , Then try to connect to the server again before abandoning the statement . have access to mysql_options() Set up MYSQL_OPT_RECONNECT Option to control the reconnection behavior .
    
    */
  • mysql_real_escape_string(): Special characters in escape characters , In order to be in SQL Use in statement , Also consider linking the current character set
  • mysql_real_escape_string_quote(): Special characters in escape characters , In order to be in SQL Use in statement , Consider both the current character set and the reference context of the link
  • mysql_real_query(): Executes the specified count string SQL Inquire about
  • mysql_refresh(): Refresh or reset tables and caches
  • mysql_reload(): Tell the server to reload the authorization table
  • mysql_reset_connection(): Reset link to clear session state
  • mysql_rollback(): Roll back the transaction
  • mysql_row_seek(): Use from mysql_row_tell() The value returned , Looking for row offset in result set China
  • mysql_row_tell(): Return line cursor position
  • mysql_select_dn(): Select database
  • mysql_server_end(): complete MySQL C API library
  • mysql_server_init(): initialization MySQL C API library
  • mysql_session_track_get_first(): Get the first part of the session state change information
  • mysql_session_track_get_next(): Get the next part of the session state change information
  • mysql_set_character_set(): Sets the default character set for the current link .
  • mysql_set_local_infile_default(): Set up LOAD DATA LOCAL The callback handler is set to the default value
  • mysql_local_infile_handler(): Install application specific LOAD DATA LOCAL Callback handler
  • mysql_set_server_option(): Set link options
  • mysql_sqlstate(): Returns the last error SQLSTATE Error code
  • mysql_shutdown(): Shut down the database server
  • mysql_ssl_set(): Prepare to set up with the server SSL link
  • mysql_stat(): Returns the server status as a string
  • mysql_store_result(): Retrieve the full result set of the client
    MYSQL_RES *mysql_store_result(MYSQL *mysql);
    /*
     describe :
         On the move mysql_query() perhaps mysql_real_query() after , For each statement that successfully generates a result set (SELECT,SHOW,DESCRIBE,EXPLAIN,CHECK TABLE etc. ) call mysql_store_result or mysql_use_result. After completing the result set, you must also call mysql_free_result(). Other statements do not need to be called mysql_store_result() or mysql_use_result(), But there's no harm in calling in any case , No performance degradation . It can detect mysql_store_result Whether the return value of is a non-zero value to detect whether the result set is obtained .
          If multi statement support is enabled , Should be called through a loop mysql_next_result() To search mysql_query() perhaps mysql_real_query() Result , To determine if there are more results . If you want to know whether a statement should return a result set , have access to mysql_fiels_count() To check .
         mysql_store_result() Read the whole result of the query to the client , And assign MYSQL_RES structure , Store the results in this structure . If MySQL Statement did not return a result set ( for example INSERT sentence ), be mysql_store_result() return NULL. Or an error occurred and the read result set failed .
          If MySQL No row data is returned during statement execution , Returns an empty result set ( The difference between a null result set and a null pointer is that the return value .) An empty result set whose return result is not NULL. Calling mysql_store_result() And the return is not NULL After the result of , Callable mysql_num_rows() How many rows are there in the search result set .
          You can call mysql_fetch_row() Get row data from result set , Or call mysql_row_seek() and mysql_row_tell() To get or set the current row position in the result set .
     Return value :
         Point to with a result MYSQL_RES Structure pointer . If the statement does not return a result set or an error occurs , Then return to NULL. To determine if an error has occurred , Need to call mysql_error() To get error information or call mysql_errno() To get the error code , perhaps mysql_field_count() return 0
     error :
        mysql_store_result() Reset if successful mysql_error() and mysql_errno().
        CR_COMMANDS_OUT_SYNC: The command was executed in an incorrect order 
        CR_OUT_OF_MEMORY: Out of memory 
        CR_SERVER_GONE_ERROR:MySQL The server disappears 
        CR_SERVER_LOST: Disconnect from server during query 
        CR_UNKNOWN_ERROR: Unknown error 
    mysql_num_fields*/

     

    • mysql_thread_end(): Complete a thread handler
    • mysql_thread_id(): Returns the current thread id
    • mysql_thread_init(): Initialize thread handler
    • mysql_thread_safe(): If the client is compiled to be thread safe, it returns 1
    • mysql_use_result(): Start row by row result set retrieval
    • mysql_warning_count(): Back to previous SQL Statement's warning count
        The application should follow the following general process with MySQL Interact .
    1. By calling mysql_library_init() initialization MySQL Client library . This function exists in the libmysqlclient C Client library and libmysqld Embedded Server Library , So whether you are through the link -lmysqlclient Library or link -lmysqld( The embedded ) Can build a regular client program .
    2. By calling mysql_init() To initialize the linker , And call mysql_real_connect() Link to server .
    3. issue SQL Statement and process the result
    4. call mysql_close() Close link to server
    5. call mysql_libray_end() end MySQL Use of client library .
        call mysql_library_init() and mysql_library_end() The purpose of the project is to provide MySQL Proper initialization and finalization of client library . For applications linked to client Libraries , They provide improved memory management mechanisms . If you don't call mysql_library_end(), Although it will not increase the amount of memory used by the application , But some memory leak tools will detect a memory leak . For embedded applications , These two functions start and shut down the server .
        In the case of non multithreading , You can omit the mysql_library_init() Call to , because mysql_init() It will call as needed . however ,mysql_library_init() Not thread safe in a multithreaded environment , So you must call before generating any thread mysql_library_init() Or by mysql_init() Indirect calls need to use mutex to protect calls . This should be done before calling any client library functions .
        To link to the server , You need to call mysql_init() initialization MYSQL Handle ., Then use this handle , Host name , user name , Password, etc mysql_real_connect(). When the link is complete ,mysql_real_connect() Before 5.0.3 Of API Will relink flag in version (MYSQL Part of the structure ) Set to 1, Or set to in the new version 0. The value of this flag is 1 Indicates that if the statement cannot be executed due to a missing link , Try to relink the server before giving up . You can call mysql_options() Of MYSQL_OPT_RECONNECT Option to control the relink behavior . When the link is complete , call mysql_close() To terminate the link , It can't be used after closing MYSQL Handle .
        When a link is active , The client can call mysql_query() perhaps mysql_real_query() take SQL Send to server . The difference between the two is mysql_query() The query is expected to be specified as null a null-terminated string , and mysql_real_query You need to evaluate the string . If the string contains binary data , Must be used mysql_real_query().
        For each non SELECT Inquire about ( for example INSERT,UPDATE,DELETE), You can call mysql_affected_rows() To find the number of rows affected by the change . about SELECT Inquire about , The selected row is retrieved as the result set .( Please note that , Some statements are similar SELECT, Because they go back to the line . These statements include SHOW,DESCRIBE,EXPLAIN These to SELECT Statements are handled in the same way .)
        The client has two ways to process the result set , One way is by calling mysql_store_result() Retrieve the entire result set at once . This function gets all the rows returned by the query from the server , And store them in the client . The second way is for the client to call mysql_use_result() To start row by row result set retrieval . This function initializes the retrieval , But no row data is fetched from the server .
            In both cases , You can call mysql_fetch_row() Visit and ask for help , Use mysql_store_result(),mysql_fetch_row() The access line is obtained from the server first ; Use mysql_use_result(),mysql_fetch_row() Access rows are rows retrieved from the server . By calling mysql_fetch_lengths() You can get information about the size of the data in each row .
            After the completion of the operation result set , Need to call mysql_free_result() To free up memory .
            These two retrieval mechanisms are complementary . Select the retrieval method that best suits each client application , In fact, clients prefer to use mysql_store_result().
            mysql_store_result One of the advantages is that the row data has been extracted to the client , You can not only access rows sequentially , You can also use mysql+_data_seek() perhaps mysql_row_seek() Move back and forth in the result set to change the position of the current row . You can mysql_num_rows() To find the number of rows . On the other hand, for large result sets ,mysql_store_result() Memory requirements can be very high , And you are likely to run out of memory .
            mysql_use_result() One advantage is that the client needs less memory for the result set , Because it maintains only one row at a time , therefore mysql_use_result Faster . The disadvantage is that you have to process every row of data quickly to avoid taking up the server , And you do not randomly access rows in the result set , Only sequential access , And the number of rows in the result set is unknown , Until you have retrieved all the rows . And even if you're sure you've found the information you need in your search , All rows must also be retrieved .
            API So that the client can respond to the statement appropriately , You don't have to wait until the statement is SELECT. You can go through each mysql_query() perhaps (mysql_real_query()) Then call mysql_store_result() To do this . If the result set call is successful , The statement is SELECT, You can read rows . If the result set call fails , Please call mysql_field_count() To determine what the results are actually expected to be . If mysql_field_count() return 0. The statement returns no data ( Table name it is INSERT,UPDATE,DELETE etc. ), And no rows are returned / If mysql_field_count() Return non 0,. The statement returns a row , But if not, the statement is a failure SELECT. An example of how to do this , May refer to mysql_field_count() Explanation .
        mysql_store_result() and mysql_use_result() You can get information about the fields that make up the character set ( Number of fields , name , Type, etc. ). You can call it repeatedly mysql_fetch_field() Or by calling mysql_fetch_field_direct() The fields in the row are numbered sequentially to access the field information in the row . You can call mysql_filed_seek() To change the current field cursor position . Setting the cursor position affects the mysql_fetch_field() Subsequent calls to . You can also call mysql_fetch_fields() Get all the field information at once .
            To detect and report errors ,MySQL adopt mysql_errno() and mysql_error() Function provides access to error information . These functions return the error code or error message of the most recently called function that may have succeeded or failed , So that you can determine when and why the error occurred .

版权声明
本文为[Gaoy9303]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224105400267g.html

Scroll to Top