#include<bits/stdc++.h>
#include<mysql/mysql.h>
using namespace std;
int main()
{
if(mysql_library_init(0,NULL,NULL)){
cout<<"hhh"<<endl;
exit(-1);// 初始化数据库
}
MYSQL mysql;
mysql_init(&mysql); //初始化一个连接句柄
unsigned int timeout = 3000;
mysql_options(&mysql, MYSQL_OPT_CONNECT_TIMEOUT, &timeout); //设置超时
if (!mysql_real_connect(&mysql, "localhost", "root", "@Luwc1009", "test", 0, NULL, 0))
{
std::cout << "Error: connect mysql failed: " << mysql_error(&mysql) << std::endl;
mysql_close(&mysql);
return -1;
}
char* stmt = const_cast<char*>("select * from people");
int length = strlen(stmt);
if (mysql_real_query(&mysql, stmt, length))
{
printf("mysql_real_query error\n");
return 0;
}
MYSQL_RES *result;
MYSQL_ROW row;
unsigned int num_fields;
unsigned int num_rows;
result = mysql_store_result(&mysql);
if (result)
{
num_fields = mysql_num_fields(result); //这里获取结果集中的列数
printf("num_fields = %d\n", num_fields);
while((row = mysql_fetch_row(result))) //遍历结果集中每一行
{
unsigned long *lengths;
lengths = mysql_fetch_lengths(result); //获取每个字段的实际长度
for (unsigned int i = 0; i < num_fields; ++i) //输出每个字段
{
printf("%s ", row[i] ? row[i] : NULL);
}
}
printf("\n");
}
mysql_free_result(result); //释放内存
mysql_close(&mysql);
mysql_library_end();
}
编译命令是:g++ -g main2.cpp -o test mysql_config --cflags --libs