Access MySQL using C language

Source: Internet
Author: User

Connecting to the MySQL database using C language involves two steps:
1. initialize a link handle structure;
2. actually connect
First, use mysql_init to initialize the connection handle:
# Include <mysql. h>
MySQL * mysql_init (MySQL *);
Generally, if you pass null to this routine, it returns a pointer pointing to the new connection handle structure. If you pass an existing structure, it will be reinitialized,
If an error occurs in this routine, null is returned.
So far, you have to allocate knowledge and initialize a structure. You also need to use mysql_real_connect to provide parameters for a connection.
MySQL * mysql_real_connect (MySQL * connection, const char * server_host,
Const char * SQL _user_name, const char * SQL _password, const char * db_name,
Unsigned int port_number, const char * unix_socket_name, unsigned int flags );
The pointer connection must point to the structure initialized by mysql_init.
Server_host can be either a host name or an IP address.
SQL _user_name and SQL _password have the same meaning as their literal meanings. If the login name is null, assume that the login name is the login ID of the current Linux User.
If the password is null, you can only access data on the server without a password.
Port_number and unix_socket_name should be 0 and null respectively, unless you change the default settings for MySQL installation. They use the appropriate values by default.
Finally, the flags parameter is used to perform or operations on some defined bit modes.
If the connection fails, it returns NULL. The mysql_error function can provide helpful information.
After using the connection, when the program Exits normally, you need to call the function mysql_close () as follows ();
Void mysql_close (MySQL * connection );
This will close the connection.
You can set some options for the mysql_option routine (which can only be called between mysql_init and mysql_real_connect.
Int mysql_option (MySQL * connection, Enum option_to_set, const char * argument );
Because only one option can be set for mysql_option at a time, you must call it once to set one option.
Description of the actual parameter types of The enum Option
Mysql_opt_timeout const unsigned int * number of seconds waiting before connection timeout
Mysql_opt_compress none, uses the compression mechanism in the null network connection
Mysql_opt_command const char * Command sent after each connection is established

Execute SQL statements
The main API functions that execute SQL statements are named as follows:
Int mysql_query (MySQL * connection, const char * query );
If the request is successful, 0 is returned.
1. SQL statement that does not return data
My_ulonglong mysql_affected_rows (MySQL * connection );
The returned value is an unsigned long integer. During printf printing, we recommend that you use % lu to convert it to an unsigned long integer. The returned number of rows is affected by the previous SQL statement.
2. Statements for returning data
Function for extracting all data at a time
Mysql_res * mysql_store_result (MySQL * connecion );
Obviously, you need to use this function after mysql_query is successfully called. This function will immediately save all the data returned in the client.
After mysql_store_result is successfully called, you need to call mysql_num_rows to obtain the number of returned records.
My_ulonglong mysql_num_rows (mysql_res * result );
This function accepts the structure returned by mysql_store_result and returns the number of rows in the structure set.
Mysql_row mysql_fetch_row (mysql_res * result );
This function extracts a row from the result structure obtained using mysql_store_result and places it in a row structure. Returned when data is used up or an error occurs
Null.
Void mysql_data_seek (mysql_res * result, my_ulonglong offset );
This function is used to jump in the result set. The setting will be returned by the next mysql_fetch_row operation. The value of the offset parameter is a row number, which must be in
0 to the range where the total number of rows in the result set is reduced by 1,
Mysql_row_offset mysql_row_tell (mysql_res * result );
This function returns an offset value indicating the current position in the result set. It is not a row number, you cannot use it for mysql_data_seek
Mysql_row_offset mysql_row_seek (mysql_res * result, mysql_row_offset offset );
This will move the current position in the result set and return the previous position.
Extract one row of data at a time
MySQL _ res * mysql_use_result (MySQL * connection );

To extract data row by row, we will use mysql_use_result instead of mysql_store_result.
Mysql_res * mysql_use_result (MySQL * connection );
The mysql_field_count function provides some basic information about the query result. It accepts the connected object and returns the number of fields (columns) in the result set.

Unsigned int mysql_field_count (MySQL * conneciton );

#include <stdlib.h>#include <stdio.h>#include "mysql.h"MYSQL my_connection;MYSQL_RES *res_ptr;MYSQL_ROW sqlrow;void display_row();int main(int argc, char *argv[]) {   int res;   mysql_init(&my_connection);     if (mysql_real_connect(&my_connection, "localhost", "rick",                                               "secret", "foo", 0, NULL, 0)) {   printf("Connection success\n");      res = mysql_query(&my_connection, "SELECT childno, fname, age FROM children WHERE age > 5");   if (res) {      printf("SELECT error: %s\n", mysql_error(&my_connection));   } else {      res_ptr = mysql_use_result(&my_connection);      if (res_ptr) {         while ((sqlrow = mysql_fetch_row(res_ptr))) {            printf("Fetched data...\n");    display_row();         }         if (mysql_errno(&my_connection)) {            printf("Retrive error: %s\n", mysql_error(&my_connection));         }         mysql_free_result(res_ptr);      }   }   mysql_close(&my_connection);   } else {      fprintf(stderr, "Connection failed\n");      if (mysql_errno(&my_connection)) {         fprintf(stderr, "Connection error %d: %s\n",                  mysql_errno(&my_connection), mysql_error(&my_connection));      }   }   return EXIT_SUCCESS;}void display_row() {   unsigned int field_count;   field_count = 0;   while (field_count < mysql_field_count(&my_connection)) {      printf("%s ", sqlrow[field_count]);      field_count++;   }   printf("\n");}

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.