C ++ can be connected to MySQL in two ways. The first method is to connect using ADO, and the second method is to connect using MySQL's own API functions. Either way, you need to install the MySQL database first. It is best to install navicat for MySQL to facilitate database operations.
Here we will only introduce the second method: using MySQL's own API function connection.
1. to connect to the MySQL database with vs2005, you must first configure the environment variables. The specific steps are as follows:
(1) Add the include file directory: Project --> properties --> Configuration properties --> C/C ++ --> General --> Add the include directory, add "C: \ Program Files \ mysql server 5.5 \ include" to this directory. Modify the path according to the local installation path.
(2) Add a library (libs) file directory: Project --> properties --> Configuration properties --> linker --> General --> Add a library directory, and add: "C: \ Program Files \ mysql server 5.5 \ Lib ". Modify the path according to the local installation path.
(3) Add the statement in the source program of the database operation: # pragma comment (Lib, "libmysql. lib ")
2. Create a database table, as shown in figure
3. The following is a simple C ++ program. The function is to connect to the database and add information to the database.
# Include <iostream> # include "Winsock. H "# include" MySQL. H "# include <string> using namespace STD; # pragma comment (Lib," libmysql. lib ") void opendb (); void closedb (); void commitdb (); void insertdb (string name, string sex, int number); void startrun (); void endrun (); MySQL * MySQL; char dbuser [30] = "root"; // database username char dbpasswd [30] = "123 "; // Database Password char dbip [30] = "localhost"; // server char dbname [50] = "testdb"; // database name char Ta Blename [50] = "Table2"; // data table name void main () {string name = "Jack"; string sex = "male"; int number = 2013; startrun (); insertdb (name, sex, number); commitdb (); endrun ();} void opendb () {MySQL = mysql_init (null); If (! Mysql_real_connect (MySQL, dbip, dbuser, dbpasswd, dbname, 3306, null, 0) {cout <"database connection error! "<Endl;} else {cout <" database connection successful! "<Endl ;}} void closedb () {If (MySQL) mysql_close (MySQL); MySQL = NULL;} void insertdb (string name, string sex, int number) {char num [30]; sprintf (Num, "% d", number); string tablename_s = tablename; string pquery = "insert into '" + tablename_s + "' (name, sex, num) values ('"+ name +"', '"+ sex +"', '"+ num +"'); "; mysql_query (MySQL, pquery. c_str ();} void commitdb () {If (mysql_commit (MySQL) cout <"Commit error! "<Endl;} void startrun () {If (MySQL) closedb (); opendb () ;}void endrun () {If (MySQL) {commitdb (); closedb ();}}
4. After running the program, open the database for verification: