280 字
1 分钟
Using C++ to Operate a MySQL Database
MySQL 5 Installation
Open a command line with administrator privileges, go to the /bin directory, and enter mysqld.exe --install&&net start mysql
Changing the Password
For the first change, enter mysqladmin -u root password "new_password".
To change an existing password, enter mysqladmin -u root -p password "new_password", then enter the original old password.
IDE Settings
First, add mysql5\include to the include directory.
Add mysql5\lib\opt to the lib directory.
(Optional) Add libmysql.lib to the lib files linked by the linker.
If you can’t figure out how to add libmysql.lib, you can skip this step
Using C++ Code to Connect to and Operate the Database
Required Header Files
First, include the following header files
#include <winsock2.h>#include <mysql.h>#pragma comment(lib,"libmysql.lib") //If you've set libmysql.lib in the IDE, you don't need this line, but adding it won't hurt eitherConnecting to the Database
MYSQL mysqlconn;mysql_init(&mysqlconn);char * host="127.0.0.1"; //Server addressint port=3306; //Portchar * username="root"; //Usernamechar * password="1234567890"; //Passwordchar * dbname="virus"; //Database name
(mysql_real_connect(&mysqlconn,host,username,password,dbname,port,NULL,CLIENT_FOUND_ROWS) != NULL)?cout<<"success"<<endl:cout<<"fail"<<endl;
mysql_query(&mysqlconn,"set names gbk"); //After connecting, set the encoding to GBKReading Data from the Database
void getdata(){ MYSQL_RES * mysql_res; MYSQL_FIELD * mysql_field; MYSQL_ROW mysql_row; char * sql="select * from virus_data where city_deadCount>50";
if(mysql_query(&mysqlconn,sql)==0) { cout<<"get data success"<<endl; mysql_res=mysql_store_result(&mysqlconn); if(mysql_res) { int fiendcount=mysql_num_fields(mysql_res); int rowcount=mysql_num_rows(mysql_res); cout<<fiendcount<<endl; cout<<rowcount<<endl;
for(int i=0;i<fiendcount;i++) { mysql_field=mysql_fetch_field(mysql_res); cout<<mysql_field->name<<" "; } cout<<endl;
for(int i=0;i<rowcount;i++) { mysql_row=mysql_fetch_row(mysql_res); for(int ja=0;ja<fiendcount;ja++) { cout<<mysql_row[ja]<<" "; } cout<<endl; } } }else{ cout<<"get data fail"<<endl; }}Modifying Data in the Database
string sql;sqla = "update item set qty=" + tmp + " where itemid='" + itemid + "'"; //Updatesqlb = "delete from user where userid='" + userid + "'"; //Deletesqlc = "insert into datemax(date,value) values('" + date + "','" + "1" + "');"; //Insertmysql_query(&mysqlconn, sql);Project Example
Using C++ to Operate a MySQL Database
https://tski.uk/blog/en/cpp-opt-mysql/