#include <iostream>
#include <vector>
#include <string>
#include <mysql.h>
using namespace std;
int main()
{
ios::sync_with_stdio (false);
MYSQL connection;
mysql_init (&connection);
mysql_real_connect (&connection,"localhost", "root", "1234",
"world", 3306, nullptr, 0);
// mysql_query 是一个值-结果函数
int query_success = mysql_query (&connection, "SELECT * FROM city LIMIT 10");
if (query_success == 0){
// 保存查询结果到 result
MYSQL_RES* result = mysql_store_result (&connection);
if (result){
std::cout << "Number of result: "
<< static_cast<size_t>(mysql_num_rows(result)) << "
";
// 获取列名
MYSQL_FIELD* field;
vector<string> column;
while ((field = mysql_fetch_field (result))){
column.emplace_back(field->name);
}
// 或者使用 mysql_num_fields(result); 得到结果的行数
for (const auto& col : column){
cout << col << " ";
}
cout << "
";
MYSQL_ROW row;
while ((row = mysql_fetch_row(result))){
for (size_t i = 0; i != column.size(); ++i){
std::cout << row[i] << " ";
}
cout << "
";
}
}
mysql_free_result(result);
}
mysql_close(&connection);
return 0;
}
再做一些小改动:
#include <iostream>
#include <vector>
#include <string>
#include <mysql.h>
using namespace std;
int main()
{
ios::sync_with_stdio (false);
MYSQL connection;
mysql_init (&connection);
mysql_real_connect (&connection,"localhost", "root", "1234",
"world", 3306, nullptr, 0);
// mysql_query 是一个值-结果函数
int query_success = mysql_query (&connection, "SELECT * FROM city");
if (query_success == 0){
// 保存查询结果到 result
MYSQL_RES* result = mysql_store_result (&connection);
if (result){
cout << "Number of result: "
<< static_cast<size_t>(mysql_num_rows(result)) << "
";
MYSQL_FIELD* field;
while ((field = mysql_fetch_field (result))){
cout << field->name << " ";
}
cout << "
";
MYSQL_ROW row;
auto const field_num = mysql_num_fields(result);
while ((row = mysql_fetch_row(result))){
for (size_t i = 0; i != field_num; ++i){
std::cout << row[i] << " ";
}
cout << "
";
}
}
mysql_free_result(result);
}
mysql_close(&connection);
return 0;
}