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); //成功返回结构体指针,失败返回NULL my_ulonglong mysql_num_row(MYSQL_RES * result); //减速实际返回的行数 MYSQL_ROW mysql_fetch_row(MYSQL_RES * result); //从mysql_store_result()中得到结果的结构体,并从中检索单个行,当没有更多的数据,或者出错时,返回NULL void 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); } }查看更多关于MySQL学习笔记_12_Linux下C++/C连接MySQL数据库(二)--返的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did4278