標籤:c++ 串連 mysql c++ mysql 資料庫 備忘
使用VS2008作為IDE, 前期準備操作:
1. 項目屬性 C++ 附加元件封裝含目錄 路徑為 mysql 安裝目錄的include
如:"C:\Program Files (x86)\MySQL\MySQL Server 5.6\include"
2. 連結器 常規 附加庫目錄 路徑為 mysql 安裝目錄的lib
"C:\Program Files (x86)\MySQL\MySQL Server 5.6\lib"
3. 連結器 輸入 附加依賴項 路徑為 mysql 為 libmysql.lib 所在目錄,
如 "C:\Program Files (x86)\MySQL\MySQL Server 5.6\lib\libmysql.lib"
註:這裡的檔案目錄路徑因為有空格,所以一定要用 " " 包含起來!!!
4. 將 mysql 目錄下的 libmysql.DLL 檔案拷貝到 debug 目錄下,這個很重要!!!!
代碼:
#include <iostream>#include <winsock2.h>#include <string>#include "mysql.h"#pragma comment(lib, "libmysql.lib");using namespace std;int main(){MYSQL mysql;mysql_init(&mysql);// 初始化MYSQL *ConnStatus = mysql_real_connect(&mysql,"localhost","root","","sky",3306,0,0);if (ConnStatus == NULL){// 串連失敗int i = mysql_errno(&mysql);string strError= mysql_error(&mysql);cout <<"Error info: "<<strError<<endl;return 0;}cout<<"Mysql Connected..."<<endl;string strsql;MYSQL_RES *result=NULL;// 資料結果集// 插入操作strsql = "insert into t1 values(2,'lyb')";if(0 == mysql_query(&mysql,strsql.c_str())){cout<<"insert ok"<<endl;}else{cout<<"insert error"<<endl;return 0;}//查詢strsql = "select * from t1";if(0 == mysql_query(&mysql,strsql.c_str())){cout<<"select ok"<<endl;result = mysql_store_result(&mysql);// 擷取結果放到 result中}else{cout<<"select error"<<endl;return 0;}//返回記錄集總數int rowcount = mysql_num_rows(result);cout<<"row count :"<<rowcount<<endl;//取得表的欄位數組 數量unsigned int feildcount = mysql_num_fields(result);cout<<"feild count: " << feildcount <<endl;cout << endl;//欄位指標 遍曆欄位MYSQL_FIELD *feild = NULL;for(unsigned int i = 0; i<feildcount;i++){feild = mysql_fetch_field_direct(result,i);cout<<feild->name<<"\t";}cout << endl;//行指標 遍曆行MYSQL_ROW row =NULL;while (NULL != (row = mysql_fetch_row(result)) ){for(int i=0; i<feildcount;i++){cout<<row[i]<<"\t";}cout<<endl;}cout<<endl;//釋放結果集 關閉資料庫mysql_free_result(result);mysql_close(&mysql);mysql_library_end();return 0;}//官方文檔參考//http://dev.mysql.com/doc/refman/5.1/zh/apis.html
運行結果
官方文檔參考 http://dev.mysql.com/doc/refman/5.1/zh/apis.html