Connect to the mysql database through C ++ APIs for addition, deletion, modification, and query _ MySQL

Source: Internet
Author: User
Connecting to the mysql database using C ++ APIs for addition, deletion, modification, and query I. environment configuration

1. install mysql and create a new C ++ console project (starting from the simplest one, this will be done and can be transplanted to any c ++ project). set it in vs2010, project -- property -- VC ++ directory -- contains Directory, add the absolute path of mysql server \ include, for example, C: \ Program Files \ MySQL Server 5.6 \ include. Copy libmysql. lib and libmysql. dll in the mysql server \ lib folder to the project directory.

(You can also copy the include file to the project directory and set the relative path in the VC ++ directory)

If you are installing the wamp integrated development kit, it does not matter if you cannot find the include and lib. you can find the include folder and libmysql under the root directory of the mysql installation-free version. lib and libmysql. copy the dll to the project directory and set the VC ++ directory.

Create a database test and a table user,


Note that some fields must be UTF-8 or gbk encoded to prevent Chinese garbled characters.

2. add the dependencies wsock32.lib and libmysql to the project. lib, one method is project -- property -- linker -- input -- additional dependency, and the other is to use # pragma comment (lib, "xxx. lib ")

3. add the header files "mysql. h" and WinSock. h to the program.

II. Sample code

# Include
 
  
# Include
  
   
// Be sure to include this, or winsock2.h # include "include/mysql. h "// introduce the mysql header file (one is to set it in the vc directory, the other is to copy the folder to the project directory, and then include it in this way) # include
   
    
// Contains additional dependencies. you can also set # pragma comment (lib, "wsock32.lib") # pragma comment (lib, "libmysql. lib ") MYSQL mysql; // mysql connects to MYSQL_FIELD * fd; // The array of field columns char field [32] [32]; // The array MYSQL_RES * res; // This structure indicates a query result set MYSQL_ROW column of the returned row; // A type-safe representation of the data type of a row, char query [150]; // query statement bool ConnectDatabase (); // function declaration void FreeConnect (); bool QueryDatabase1 (); // query 1 bool QueryDatabase2 (); // query 2 bool InsertData (); Bool ModifyData (); bool DeleteData (); int main (int argc, char ** argv) {ConnectDatabase (); QueryDatabase1 (); InsertData (); QueryDatabase2 (); modifyData (); QueryDatabase2 (); DeleteData (); QueryDatabase2 (); FreeConnect (); system ("pause"); return 0;} // connect to the database bool ConnectDatabase () {// initialize mysqlmysql_init (& mysql); // Connect to mysql. if the database returns false, the connection fails. if the return value is true, the connection succeeds. if (! (Mysql_real_connect (& mysql, "localhost", "root", "", "test", 0, NULL, 0) // host, user name, password, database name, port number (default 0 or 3306 can be written), you can first write a parameter and then pass in {printf ("Error connecting to database: % s \ n ", mysql_error (& mysql); return false;} else {printf ("Connected... \ n "); return true ;}/// release the resource void FreeConnect () {// release the resource mysql_free_result (res); mysql_close (& mysql );} ********** * *********************** // In fact, all databases All operations are completed by writing an SQL statement, and then using mysql_query (& mysql, query), including creating a database or table, adding, deleting, modifying, and querying/querying data bool QueryDatabase1 () {sprintf (query, "select * from user"); // execute the query statement. here all queries are queried, and the user is the table name, without quotation marks, use strcpy or mysql_query (& mysql, "set names gbk"); // SET the encoding format (set names gbk is also supported ), otherwise, the Chinese characters in cmd are garbled. // 0 is returned, and 1 is returned. if (mysql_query (& mysql, query )) // execute the SQL statement {printf ("Query failed (% s) \ n", mysql_error (& mysql); return false ;} else {printf ("query success \ n");} // get the result Set if (! (Res = mysql_store_result (& mysql) // Obtain the returned result set {printf ("Couldn't get result from % s \ n ", mysql_error (& mysql); return false;} // Print the number of data rows printf ("number of dataline returned: % d \ n", mysql_affected_rows (& mysql )); // Obtain the field information char * str_field [32]; // define a string array to store the field information for (int I = 0; I <4; I ++) // Obtain the field name {str_field [I] = mysql_fetch_field (res)-> name ;}for (int I = 0; I <4; I ++) // Print the field printf ("% 10s \ t", str_field [I]); printf ("\ n "); // Print the obtained data while (column = mysql_fetch_row (res) // when the number of fields is known, obtain and print the next {printf ("% 10s \ t % 10s \ t % 10s \ t % 10s \ n", column [0], column [1], column [2], column [3]); // column is a column array} return true;} bool QueryDatabase2 () {mysql_query (& mysql, "set names gbk "); // returns 0 for successful query and 1 for failed query if (mysql_query (& mysql, "select * from user ")) // execute the SQL statement {printf ("Query failed (% s) \ n", mysql_error (& mysql); return false ;} else {printf ("query success \ n");} res = mysql_store_result (& mysql); // Print the number of data rows printf ("number of dataline returned: % d \ n ", mysql_affected_rows (& mysql); for (int I = 0; fd = mysql_fetch_field (res); I ++) // Obtain the field name strcpy (field [I], fd-> name); int j = mysql_num_fields (res); // gets the number of columns for (int I = 0; I
    
     
Running result:




III. mysql API summary
  • Mysql_affected_rows () returns the number of rows affected by the latest UPDATE, DELETE, or INSERT query.
  • Mysql_close () closes a server connection.
  • Mysql_connect () connects to a MySQL server. This function is not recommended; use mysql_real_connect () instead.
  • Mysql_change_user () changes the user and database on an open connection.
  • Mysql_create_db () creates a database. This function is not recommended, but the SQL command CREATE DATABASE is used.
  • Mysql_data_seek () searches for any row in a query result set.
  • Mysql_debug () uses the given string for DBUG_PUSH.
  • Mysql_drop_db () discards a database. This function is not recommended, but the SQL command DROP DATABASE is used.
  • Mysql_dump_debug_info () allows the server to write debugging information to the log file.
  • Mysql_eof () determines whether the last row of a result set has been read. This function is opposed; mysql_errno () or mysql_error () can be used on the contrary.
  • Mysql_errno () returns the error number of the recently called MySQL function.
  • Mysql_error () returns the error message of the recently called MySQL function.
  • Use mysql_escape_string () to escape special characters from strings in SQL statements.
  • Mysql_fetch_field () returns the type of the field in the next table.
  • Mysql_fetch_field_direct () returns the type of a table field and a field number.
  • Mysql_fetch_fields () returns an array of all field structures.
  • Mysql_fetch_lengths () returns the length of all columns in the current row.
  • Mysql_fetch_row () gets the next row from the result set.
  • Mysql_field_seek () place the column cursor on a specified column.
  • Mysql_field_count () returns the number of result columns of the latest query.
  • Mysql_field_tell () returns the cursor position for the last mysql_fetch_field () field.
  • Mysql_free_result () releases the memory used by a result set.
  • Mysql_get_client_info () returns the customer version information.
  • Mysql_get_host_info () returns a string that describes the connection.
  • Mysql_get_proto_info () returns the protocol version used by the connection.
  • Mysql_get_server_info () returns the server version number.
  • Mysql_info () returns information about the recently executed query.
  • Mysql_init () obtains or initializes a MYSQL structure.
  • Mysql_insert_id () returns the ID generated by the previous query for the AUTO_INCREMENT column.
  • Mysql_kill () kills a given thread.
  • Mysql_list_dbs () returns the database name that matches a simple regular expression.
  • Mysql_list_fields () returns the column name that matches a simple regular expression.
  • Mysql_list_processes () returns a table of the current server thread.
  • Mysql_list_tables () returns the table name that matches a simple regular expression.
  • Mysql_num_fields () returns the number of duplicate columns in a result set.
  • Mysql_num_rows () returns the number of rows in a result set.
  • Mysql_options () sets the connection options for mysql_connect.
  • Mysql_ping () checks whether the connection to the server is working and reconnects if necessary.
  • Mysql_query () executes an SQL query specified as an empty string.
  • Mysql_real_connect () connects to a MySQL server.
  • Mysql_real_query () executes an SQL query specified as a string with a count.
  • Mysql_reload () tells the server to reinstall the authorization table.
  • Mysql_row_seek () searches for rows in the result set and uses the values returned from mysql_row_tell.
  • Mysql_row_tell () returns the cursor position of the row.
  • Mysql_select_db () connects to a database.
  • Mysql_shutdown () disables the database server.
  • Mysql_stat () returns the server status as a string.
  • Mysql_store_result () retrieves a complete set of results for the customer.
  • Mysql_thread_id () returns the ID of the current thread.
  • Mysql_use_result () initializes the retrieval of a result set in one row and one row.
  • 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.