直接上代码!!!!
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql.h>
#include <iostream>
using namespace std;
int main()
{
const char user[] = "root"; //username
const char pswd[] = "123456"; //password
const char host[] = "localhost"; //or"127.0.0.1"
const char database[] = "facedb"; //database
unsigned int port = 3306; //server port
MYSQL myCont;
MYSQL_RES *result=NULL;
MYSQL_ROW row;
MYSQL_FIELD *fd=NULL;
char column[32][32];
int res;
unsigned long num_col;
unsigned long num_row;
int i = 0;
mysql_init(&myCont);
char sql[1000];
if (mysql_real_connect(&myCont, host, user, pswd, database, port, NULL, 0))
{
cout << "connect success!!!!!" << endl;
}
else
{
cout << "connect fail!!!" << endl;
}
mysql_query(&myCont,"SET NAMES GBK");//设置编码格式
strcpy(sql, "select * from result");
res = mysql_real_query(&myCont, sql, strlen(sql));
result = mysql_store_result(&myCont);
if (!result)
{
cout << "读取结果失败!!" << endl;
}
num_row = (unsigned long)mysql_num_rows(result); //获取行数
num_col = (unsigned long)mysql_num_fields(result);//获取列数
cout << "number of row:" << num_row << endl;
cout << "number of col:" << num_col << endl;
//while (fd= mysql_fetch_field(result)) //获取列名
//{
// printf("%s\t", fd->name);
//}
while (fd = mysql_fetch_field(result))//为了便于控制,我们将获取的列名保存到二维数组中。
{
strcpy(column[i], fd->name);//拷贝到二维数组中
printf("%s\t", column[i]);
i++;
}
printf("\n");
while (row = mysql_fetch_row(result))//获取行数据
{
for (i = 0; i < num_col; i++)
{
printf("%s\t", row[i]);
}
printf("\n");
}
mysql_free_result(result);//释放结果资源
mysql_close(&myCont);//断开连接
return 0;
}