C ++ reading and writing MySQL classic

Source: Internet
Author: User
I have read many articles about how to operate MySQL Databases in C or C ++, and most of them are too difficult. Even some of them do not have good organizational texts, which is hard for beginners to accept, even C ++ or C experts are hard to understand. The purpose of this article is not anything else. I will tell you to use MySQL's c API to directly operate Mysql Data and make efficient encapsulation, it can help developers greatly improve the efficiency of using MySQL c api to operate MySQL databases. Directly go to the topic: 1. Prepare various files required in the/MySQL Server 5.0/lib/OPT directory after the MySQL database is installed. We only need the following files: libmysql. liblibmysql. DLL also requires several files in the/MySQL Server 5.0/include directory: Prepare the basic socket file. Find the files in the installation directory Microsoft Visual Studio/vc98/lib of VC: ws2_32.lib prepare these files first. 2. Use the VC Appwizard to create a Win32 console application. In fact, it can be a dialog project or another type of project, for example, the project name is cmysql3. copy the file you just prepared to your project directory, which is in the same directory as the common CPP file. 4. After the project is created, in the VC menu bar, click Project> Settings. In the displayed dialog box, select the link label to go to link settings. In the object/library modules box, add libmysql. lib [has a space] ws2_32.lib5. Add the following two files in the Project Creation: First file header file: vspdctomysql. h/**************************** MySql in C ******** ***********************//*************** * ******** 2007-03-07 ************************* ***** * ********************************/# include <stdio. h> # include <string> # include <afxsock. h> # include "MySQL. H "using namespace STD; Class vspdctomysql {public: // variable MySQL;/* constructor and constructor */vspdctomysql ();~ Vspdctomysql ();/* main function: Initialize Database Connection database set character set entry parameter: Host: MySQL Server IP port: Database port DB: Database Name User: Database User passwd: database User Password charset: Expected Character Set MSG: returned message, including the error message exit parameter: INT: 0 indicates success; 1 indicates failure */INT connmysql (char * host, char * port, char * dB, char * user, char * passwd, char * charset, char * MSG);/* main functions: query data entry parameters: SQL: the queried SQL statement cnum: Number of columns queried MSG: returned messages, including the output parameter of the error message: string to place the returned data. Multiple records are separated by 0x06, multiple columns are separated by 0x05. If the returned length is 0, it indicates the dance result */string selectdata (char * SQL, int cnum, char * MSG)./* main functions: insert data entry parameter SQL: Query SQL statement MSG: returned message, including the error message exit parameter: INT: 0 indicates success; 1 indicates failure */INT insertdata (char * SQL, char * MSG);/* main function: Modify the data entry parameter SQL: Query SQL statement MSG: returned message, including the error message exit parameter: INT: 0 indicates success; 1 indicates failure */INT updatedata (char * SQL, char * MSG);/* main function: delete data entry parameter SQL: Query SQL statement MSG: returned message, including the exit parameter of the error message: INT: 0 indicates success; 1 indicates failure */INT deletedata (char * SQL, char * MSG);/* main functions: close database connection */void closemysqlconn ();}; The second file implementation file: vspdctomysql. cpp  /**************************** MySql in C ******** ***********************//*************** * ******** 2007-03-07 ************************* ***** * ********************************/# include "stdafx. H "# include" vspdctomysql. H "vspdctomysql: vspdctomysql () {} vspdctomysql ::~ Vspdctomysql () {}// initialization data int vspdctomysql: connmysql (char * Host, char * port, char * dB, char * user, char * passwd, char * charset, char * MSG) {If (mysql_init (& MySQL) = NULL) {MSG = "in1_mysql handle error"; return 1 ;}if (mysql_real_connect (& MySQL, host, user, passwd, DB, 0, null, 0) = NULL) {MSG = "failed to connect to database: error"; return 1 ;}if (mysql_set_character_set (& MySQL, "GBK ")! = 0) {MSG = "mysql_set_character_set error"; return 1;} return 0;} // query data string vspdctomysql: selectdata (char * SQL, int cnum, char * MSG) {mysql_row m_row; mysql_res * m_res; char SQL [2048]; sprintf (SQL, SQL); int rnum = 0; char Rg = 0x06; // row-separated char CG = {0x05}; // field-separated if (mysql_query (& MySQL, SQL )! = 0) {MSG = "select ps_info error"; Return "";} m_res = mysql_store_result (& MySQL); If (m_res = NULL) {MSG = "select username error"; Return "";} string STR (""); While (m_row = mysql_fetch_row (m_res) {for (INT I = 0; I <cnum; I ++) {STR + = m_row [I]; STR + = RG;} STR + = RG; rnum ++;} mysql_free_result (m_res ); return STR;} // insert data int vspdctomysql: insertdata (char * SQL, char * MSG) {char SQL [2048]; SP Rintf (SQL, SQL); If (mysql_query (& MySQL, SQL )! = 0) {MSG = "insert data error"; return 1 ;}return 0 ;}// update data int vspdctomysql: updatedata (char * SQL, char * MSG) {char SQL [2048]; sprintf (SQL, SQL); If (mysql_query (& MySQL, SQL )! = 0) {MSG = "update data error"; return 1 ;}return 0 ;}// delete data int vspdctomysql: deletedata (char * SQL, char * MSG) {char SQL [2048]; sprintf (SQL, SQL); If (mysql_query (& MySQL, SQL )! = 0) {MSG = "delete data error"; return 1;} return 0;} // close the database connection void vspdctomysql: closemysqlconn () {mysql_close (& MySQL );} 6. Add some code in the main function (if it is another project level or not the main function, it may be a code block in a button). The Code is added as follows: # include "stdafx. H "# include" vspdctomysql. H "int main (INT argc, char * argv []) {char * Host =" MySQL Server IP "; char * user =" root "; char * Port = "3306"; char * passwd = "User Password"; char * dbname = "Database Name"; char * charset = "GBK"; // supports Chinese Cha R * MSG = ""; // message variable // initialize vspdctomysql * vspdctomysql = new vspdctomysql; If (vspdctomysql-> connmysql (host, port, dbname, user, passwd, charset, MSG) = 0) printf ("connection successful/R/N"); else printf (MSG); // query char * SQL = "Select IDS, username, passwd, address from vcaccesstest "; string STR = vspdctomysql-> selectdata (SQL, 4, MSG); If (Str. length ()> 0) {printf ("query succeeded/R/N"); printf (Str. data (); printf ("/R/N");} else {Printf (MSG);} // insert SQL = "insert into vcaccesstest (IDs, username, passwd, address) values (4, 'my', '123 ', 'test address') "; if (vspdctomysql-> insertdata (SQL, MSG) = 0) printf (" inserted successfully/R/N "); // update SQL = "Update vcaccesstest set username = 'modified', passwd = '000000' where IDs = 3"; if (vspdctomysql-> updatedata (SQL, MSG) = 0) printf ("updated successfully/R/N"); // Delete SQL = "delete from vcaccesstest where IDs = 3"; if (vspdctomysql-> delet Edata (SQL, MSG) = 0) printf ("Deleted/R/N"); vspdctomysql-> closemysqlconn (); Return 0;} 7. Check whether the database table exists, (The tables and fields in the program are the content in my database. You have to handle your SQL statements by yourself. You can check the content of the SQL variables in the main function. 8. Compile, run, and everything is OK. 9. To sum up, you have little to do. You have written two major files. You can call them by referring to the example. Other MySQL database files and additional files have also been prepared for you, porting to other systems is also very easy, for example, porting to Linux and UNIX is also very easy, vspdctomysql. H and vspdctomysql. CPP is basically written in standard C ++, and a small amount of modifications may be required in other systems.

 

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.