代碼:
#include
#include
#include "/usr/local/include/mysql/mysql.h" //安裝的MySQL的頭文件所在的位置
using namespace std;
string host="數據庫地址";
string user="用戶名";
string pwd="密碼";
string dbname="數據庫";
string sql="查詢語句";
unsigned int port=3309;#端口號
int status;
int main(){
MYSQL *MySQL;
mysql=MySQL_init(0);
MySQL_RES *result;
MySQL_ROW row;
if(mysql_real_connect(MySQL,host.c_str(),user.c_str(),pwd.c_str(),dbname.c_str(),port,NULL,CLIENT_FOUND_ROWS)==NULL){
cout << "connect failure!" << endl;
return EXIT_FAILURE;
}else{
cout << "connect success!" << endl;
}
mysql_set_character_set(MySQL,"gbk");
status=mysql_query(MySQL,sql.c_str());
if(status !=0 ){
cout << "query failure!" << endl;
}
cout << "the status is :" << status << endl;
result=mysql_store_result(MySQL);
while(row=MySQL_fetch_row(result)){
cout << row[1] <<"|"<< row[2] << endl;
}
MySQL_free_result(result);
mysql_close(MySQL);
}
編譯:
g++ -o test test.cpp -lmysqlclIEnt -I/usr/local/include/mysql/ -L/usr/local/lib/MySQL
後面的那些用來指定mysql安裝的時候包含路徑和庫文件路徑,具體與你機器上的MySQL安裝的路徑有關。