我之前还是一直想用 connector 来连接的,但是因为 mysql 官方提供的文件和本地的编译系统并不一样,所以需要把 connector 加上
-stdlib=libc++ 重新编译一遍。Hah 我不。
还能怎样呢?用 ODBC 吧!尝试用 mac 的 ODBC administrator,但是这个太老了,而且不方便(我觉得不方便)所以也没采用。
于是最后选择使用 mysql 的 C API 来连接数据库,而以下就是一个极为简单的例子:
#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)) << "\n"; // 获取列名 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 << "\t"; } cout << "\n"; MYSQL_ROW row; while ((row = mysql_fetch_row(result))){ for (size_t i = 0; i != column.size(); ++i){ std::cout << row[i] << "\t"; } cout << "\n"; } } 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)) << "\n"; MYSQL_FIELD* field; while ((field = mysql_fetch_field (result))){ cout << field->name << "\t"; } cout << "\n"; 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] << "\t"; } cout << "\n"; } } mysql_free_result(result); } mysql_close(&connection); return 0; }
时间: 2024-10-17 18:21:59