Linux下C++/C串連MySQL資料庫(二)--返回資料的SQL引:
返回資料的SQL是指通過查詢語句從資料庫中取出滿足條件的資料記錄
從MySQL資料庫值哦功能檢索資料有4個步驟:
1)發出查詢
2)檢索資料
3)處理資料
4)整理所需要的資料
用mysql_query()發出查詢,檢索資料可以使用mysql_store_result()或mysql_use_result(),取決與怎樣檢索資料,接著是調用mysql_fetch_row()來處理資料,最後,還必須調用mysql_free_result()以允許MySQL進行必要的整理工作。
1、一次提取所有資料
MYSQL_RES *mysql_store_result(MYSQL * connection);//成功返回結構體指標,失敗返回NULLmy_ulonglong mysql_num_row(MYSQL_RES * result);//減速實際返回的行數MYSQL_ROW mysql_fetch_row(MYSQL_RES * result);//從mysql_store_result()中得到結果的結構體,並從中檢索單個行,當沒有更多的資料,或者出錯時,返回NULLvoid mysql_free_result(MYSQL_RES * result);//使mySQL資料庫清理分配的對象,關閉串連.
樣本:
#include <iostream>#include <fstream>#include <cstdlib>#include <mysql/mysql.h>using namespace std;void mysql_err_function(MYSQL * connection);int main(){MYSQL * connection;connection = mysql_init(NULL);if (!connection){mysql_err_function(connection);} connection = mysql_real_connect(connection,"localhost","root","123456","test",0,NULL,0);if (!connection){mysql_err_function(connection);}cout << "Connection to MySQL Server is Success..." << endl;string query;getline(cin,query);int res = mysql_query(connection,query.c_str());if (res){mysql_err_function(connection);} MYSQL_RES * my_res = mysql_store_result(connection);cout << "Retrieved " << mysql_num_rows(my_res) << "rows" << endl;MYSQL_ROW sqlrow;while ((sqlrow = mysql_fetch_row(my_res))){cout << "Fetched data..." << endl;}mysql_free_result(my_res);mysql_close(connection);cout << "Connection to MySQL Server is closed!" << endl;return 0;}void mysql_err_function(MYSQL * connection){if (mysql_errno(connection)){cout << "Error " << mysql_errno(connection) << " : "<< mysql_error(connection) << endl;exit(-1);}}
2、一次提取一行資料,用於處理了大量的資料集
MYSQL_RES *mysql_use_result(MYSQL * connection); //成功返回結果集,失敗返回NULL
一次取全部資料增加了網路負載,增加了時延,但是可以保證資料的完整性。
樣本:
#include <iostream>#include <cstdlib>#include <mysql/mysql.h>using namespace std;void mysql_err_function(MYSQL * connection);int main(){MYSQL * connection;connection = mysql_init(NULL);if (mysql_real_connect(connection,"localhost","root","123456","test",0,NULL,0)){cout << "Connection to MySQL Server is Succeed..." << endl;string query;getline(cin,query);int res = mysql_query(connection,query.c_str());if (res){mysql_err_function(connection);//mysql_err_function()實現代碼參考上例}else{MYSQL_RES * my_res = mysql_use_result(connection); if (my_res){MYSQL_ROW sqlrow;while ((sqlrow = mysql_fetch_row(my_res))){cout << "Fetching the Data..." << endl;}mysql_free_result(my_res);}else{mysql_err_function(connection);}}mysql_close(connection);cout << "Connection to MySQL Server is Closed!" << endl;}else{mysql_err_function(connection);}}