MySQL study note _ Connect C ++/C to MySQL database in 11_Linux (1)

Source: Internet
Author: User

MySQL study note _ Connect C ++/C to MySQL database in 11_Linux (1)
Connecting C ++/C to the MySQL database in zookeeper Linux (1)


 

I. Preparations before connection

Raw Material: Ubuntu12.04LTS

(MySQL5.5 or a later version has been installed. The new software package, gcc/g ++ or CodeBlosks compiler)

After the above software packages are installed, we can use MySQL to complete data management, but many times we need to write a program to access MySQL. In this case, the MySQL driver header file needs to be loaded in the program, but these driver packages are not installed by default. Therefore, we need to find and install the "libmysqld-dev" package in the new version.

After the installation is complete, there will be many header files in the "/usr/include/mysql/" directory, such as mysql. h.

When compiling a program:

1. If you want to use gcc/g ++ in the command line, add the-lmysqlclient option. For example:

 

[Plain]View plaincopyprint?
  • G ++-lmysqlclient mysql_test.cc-o mysqltest
    g++ -lmysqlclient mysql_test.cc -o mysqltest

    2. If CodeBlocks is selected, set the Connection Library to mysqlclient In the build option.

    Start compilation.

     

     

    Ii. Analysis of header files and related functions

    All the functions listed in this blog are included in the header file. Therefore, add a line at the beginning of programming:

    [Cpp]View plaincopyprint?
    1. # Include
      #include 
            

       

      1. There are two steps to connect to the MySQL database using CAPI:

      1) initialize a connection handle

      2) establish a connection

      The functions used are as follows:

       

      [Cpp]View plaincopyprint?
      1. MYSQL * mysql_init (MYSQL * connection); // initialize the connection handle // The MySQL structure pointer is returned. If the connection fails, NULL is returned.
      2. MYSQL * mysql_real_connect (MYSQL * connection,
      3. Const char * server_host, const char * SQL _user_name,
      4. Const char * SQL _password, const char * db_name,
      5. Unsigned int port_number, const char * unix_socket_name,
      6. Unsigned int flags); // creates a connection // returns the MySQL structure pointer. If the connection fails, NULL is returned.
        MYSQL * mysql_init (MYSQL * connection); // initialize the connection handle // return the MySQL structure pointer. If the connection fails, return NULLMYSQL * 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 ); // establish a connection // The MySQL structure pointer is returned successfully. If the connection fails, NULL is returned.

         

        2. After the MySQL connection is completed, you need to release the MySQL connection.

        [Cpp]View plaincopyprint?
        1. Void mysql_close (MYSQL * connection); // close the connection // The connection parameter is cleared and the pointer becomes invalid.
          Void mysql_close (MYSQL * connection); // close the connection // The connection parameter is cleared and the pointer becomes invalid.

          3. mysql_options is used to set additional options and affect connection behavior. However, it can only be called between mysql_init and mysql_real_connect.

          [Cpp]View plaincopyprint?
          1. Int mysql_options (MYSQL * connection, enum mysql_option option, const char * argument); // set connection options
            Int mysql_options (MYSQL * connection, enum mysql_option option, const char * argument); // set connection options

            The option value is one of the following four values:

             

            [Plain]View plaincopyprint?
          2. MYSQL_INIT_COMMAND // The command that will be executed when you connect to the MySQL server. The command will be automatically executed again when you connect again. MYSQL_OPT_CONNECT_TIMEOUT // waiting seconds before connection timeout
          3. MYSQL_OPT_COMPRESS // compression mechanism used in network connection MYSQL_OPT_PROTOCOL // protocol type to be used, one of the mysql_protocol_type enumerated values defined in mysql. h.
            MYSQL_INIT_COMMAND // The command that will be executed when you connect to the MySQL server. The command will be automatically executed again when you connect again. MYSQL_OPT_CONNECT_TIMEOUT // waiting seconds before connection timeout MYSQL_OPT_COMPRESS // protocol type to be used in network connection MYSQL_OPT_PROTOCOL // One Of The mysql_protocol_type enumerated values defined in mysql. h.

             

            4. the above functions are run without errors. If an error occurs during database connection, we need the following two functions to handle the error message:

            [Cpp]View plaincopyprint?
            1. Unsigned int mysql_errno (MYSQL * connection); // return the error code (0 indicates an error) char * mysql_error (MYSQL * connection); // return the error message, it is a string ending with NULL.
              Unsigned int mysql_errno (MYSQL * connection); // return the error code (0 indicates an error) char * mysql_error (MYSQL * connection); // return the error message, it is a string ending with NULL.

              5. A program accesses the database not only by establishing a connection with the database, but also by executing SQL statements to query or change the data in the database. The following functions can be used to execute SQL statements.

               

              [Cpp]View plaincopyprint?
              1. Int mysql_query (MYSQL * connection, const char * query );
                int mysql_query(MYSQL *connection, const char *query);

                 

                SQL statements are divided into two types: SQL statements that return data and SQL statements that do not return data (UPDATE, DELETE, INSERT ).

                The following describes only SQL statements that do not return data.

                 

                [Cpp]View plaincopyprint?
                1. My_ulonglong mysql_affected_rows (MYSQL * connection); // return the affected rows for query. // After executing an SQL statement, you can call this function to view the execution of the SQL statement, the number of rows in the database whose data status changes to determine whether the SQL Execution is successful or not.
                  My_ulonglong mysql_affected_rows (MYSQL * connection); // return the affected rows for query. // After executing an SQL statement, you can call this function to view the execution of the SQL statement, the number of rows in the database whose data status changes to determine whether the SQL Execution is successful or not.

                   

                  Iii. Instances[Cpp]View plaincopyprint?
                  1. # Include # Include
                  2. # Include # Include
                  3. Using namespace std;
                  4. Void mysql_err_function (MYSQL * connection );
                  5. Int main ()
                  6. {// Freopen ("input.txt", "r", stdin );
                  7. MYSQL * connection;
                  8. Connection = mysql_init (NULL );
                  9. If (! Connection ){
                  10. Cout <"mysql_init failed! "<Endl;
                  11. Exit (-1 );}
                  12. If (! Mysql_real_connect (connection, "localhost", "root", "123456", "test", 0, NULL, 0 ))
                  13. {Cout <"Connection To MySQL failed! "<Endl;
                  14. Mysql_err_function (connection );}
                  15. Cout <"Connection To MySQL Server is Success..." <endl;
                  16. String str;
                  17. Getline (cin, str );
                  18. Int res = 0; int affected_count = 0;
                  19. While (str! = "Close" & str! = ""&&! Res ){
                  20. Res = mysql_query (connection, str. c_str ());
                  21. Affected_count + = mysql_affected_rows (connection );
                  22. If (res ){
                  23. If (mysql_errno (connection )){
                  24. Cout <"Error" <mysql_errno (connection) <":" <mysql_error (connection) <'\ n' <endl;
                  25. Break ;}
                  26. } Getline (cin, str );
                  27. }
                  28. Cout <"Have affected" <affected_count <"rows! "<Endl;
                  29. Mysql_close (connection );
                  30. Cout <"Connection To MySQL Server is closed..." <endl;
                  31. Return 0 ;}
                  32. Void mysql_err_function (MYSQL * connection)
                  33. {If (mysql_errno (connection ))
                  34. {Cout <"Error" <mysql_errno (connection) <":"
                  35. <Mysql_error (connection) <endl;
                  36. Exit (-1 );}
                  37. }

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.