1 #include <iostream> 2 #include <mysql.h> 3 #include <string> 4 5 #include <assert.h> 6 7 8 int main() 9 { 10 // MYSQL 初始化 11 MYSQL *ms_conn = mysql_init(NULL); 12 if (ms_conn == NULL) 13 { 14 std::cout << "Error: mysql_init failed." << std::endl; 15 return 0; 16 } 17 std::cout << "Info: mysql_init success." << std::endl; 18 19 // 连接到MYSQL 数据库服务器,最后参数CLIENT_MULTI_STATEMENTS 指定SQL 可以同时多条。 20 MYSQL *ms_temp = NULL; 21 ms_temp = mysql_real_connect(ms_conn, "localhost", "root", "123456sx", 22 "suyh", 0, NULL, CLIENT_MULTI_STATEMENTS); 23 if (ms_temp == NULL) 24 { 25 std::cout << "Error: mysql_real_connect() failed." << std::endl; 26 mysql_close(ms_conn), ms_conn = NULL; 27 return 0; 28 } 29 std::cout << "Info: mysql_real_connect() succect." << std::endl; 30 31 std::string str_sqls = ""; 32 // str_sqls += "SELECT * FROM player_data WHERE id = 100000;"; 33 // str_sqls += "SELECT * FROM player_data WHERE id = 100001;"; 34 str_sqls += "SELECT * FROM player_data WHERE id = 100002"; 35 36 // 执行SQL 语句 37 int res = 0; 38 res = mysql_real_query(ms_conn, str_sqls.c_str(), str_sqls.size()); 39 if (res != 0) 40 { 41 std::cout << "Info: query failed, sql: " << str_sqls.c_str() << std::endl; 42 mysql_close(ms_conn), ms_conn = NULL; 43 return 0; 44 } 45 std::cout << "Info: query success." << std::endl; 46 47 do 48 { 49 // 取出查询结果 50 MYSQL_RES *ms_res = mysql_store_result(ms_conn); 51 assert(ms_res != NULL); 52 53 // 结果集中的字段个数 54 unsigned int field_num = mysql_num_fields(ms_res); 55 std::cout << "fileds number is " << field_num << std::endl; 56 57 // 每个字段的结构 58 MYSQL_FIELD* field = mysql_fetch_field(ms_res); 59 assert(field != NULL); 60 61 // 取出这个结果集中的结果 62 MYSQL_ROW row_data = NULL; // typedef char ** MYSQL_ROW; 63 while (1) 64 { 65 row_data = mysql_fetch_row(ms_res); 66 if (row_data == NULL) 67 break; // 结果集中已无数据 68 69 // 一行结果中每个字段的字符数 70 unsigned long *field_lens = mysql_fetch_lengths(ms_res); 71 assert(field_lens != NULL); 72 for (int i = 0; i < field_num; ++i) 73 { 74 /* 75 std::cout << "field_lens[" << i << "] = " << field_lens[i] 76 << ", value is " << row_data[i] << std::endl; 77 */ 78 std::cout << "field name: " << field[i].name; 79 if (row_data[i] == NULL) 80 std::cout << ", value is NULL" << std::endl; 81 else 82 // std::cout << ", value is " << row_data[i] << std::endl; 83 std::cout << ", value is NOT NULL" << std::endl; 84 } 85 86 // ... // 处理结果 87 } 88 } while (mysql_next_result(ms_conn) == 0); 89 90 mysql_close(ms_conn), ms_conn = NULL; 91 return 0; 92 }