Eclipse中C++连接mysql数据库

时间:2021-05-20

本文为大家分享了Eclipse中C++连接mysql数据库的具体代码,供大家参考,具体内容如下

MinGW的配置在C连mysql里已经提到,这里只说C++跟C配置不同的地方。

首先觉得C++比C方便多了,不用生成.a连接文件,直接使用.lib文件即可

导入.h文件所在目录到C++ Compiler中的includes

添加lib文件搜索

代码:

#include <winsock.h>#include <iostream>#include <string>#include <mysql.h>using namespace std; int main() { MYSQL mydata; //初始化数据库 mysql_library_init(0, NULL, NULL); mysql_init(&mydata); mysql_options(&mydata, MYSQL_SET_CHARSET_NAME, "gbk"); //连接数据库 if (NULL != mysql_real_connect(&mydata, "localhost", "root", "111111", "mysql", 3306, NULL, 0)) { cout << "mysql_real_connect() succeed" << endl; } else { cout << "mysql_real_connect() failed" << endl; return -1; } string sqlstr = "SELECT * FROM ME_MENU"; MYSQL_RES *result = NULL; if (0 == mysql_query(&mydata, sqlstr.c_str())) { cout << "mysql_query() select data succeed" << endl; result = mysql_store_result(&mydata); int rowcount = mysql_num_rows(result); cout << "row count: " << rowcount << endl; unsigned int fieldcount = mysql_num_fields(result); MYSQL_FIELD *field = NULL; for (unsigned int i = 0; i < fieldcount; i++) { field = mysql_fetch_field_direct(result, i); cout << field->name << "\t\t"; } cout << endl; MYSQL_ROW row = NULL; row = mysql_fetch_row(result); while (NULL != row) { for (unsigned int i = 0; i < fieldcount; i++) { cout << row[i] << "\t\t"; } cout << endl; row = mysql_fetch_row(result); } } else { cout << "mysql_query() select data failed" << endl; mysql_close(&mydata); return -1; } mysql_free_result(result); mysql_close(&mydata); mysql_server_end(); system("pause"); return 0;}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章