1、创建表并写入数据
create table student( id int(11), name varchar(45), primary key (id));
insert into student values(1, "aa");
insert into student values(2, "bb");
2.接口使用
-
#include "stdio.h"
-
#include <string.h>
-
#include <algorithm>
-
#include <iostream>
-
-
-
MYSQL DbObj;//handle
-
MYSQL_RES *pRes;//results
-
MYSQL_ROW sqlrow;//rows
-
-
-
int main()
-
{
-
char tmp[255];
-
mysql_init(&DbObj);
-
-
#define MAX_COLUMN_LEN 32
-
char column[MAX_COLUMN_LEN][MAX_COLUMN_LEN];
-
-
if (!mysql_real_connect(&DbObj,"10.10.12.87" ,"zhaopf", "zhaopf", "mytest", 0, NULL, 0))
-
{
-
return 0;
-
}
-
-
sprintf(tmp,"select * from student");
-
int res=mysql_query(&DbObj,tmp);
-
pRes = mysql_use_result(&DbObj);//保存查询到的数据到result
-
if(pRes)
-
{
-
int i=0;
-
int j=mysql_num_fields(pRes);
-
for(i=0; i<j;i++)//获取列名
-
{
-
MYSQL_FIELD *fd=mysql_fetch_field(pRes);
-
bzero(column[i],sizeof(column[i]));
-
strcpy(column[i],fd->name);
-
printf("%s\t",column[i]);
-
}
-
-
printf("\n");
-
while(sqlrow=mysql_fetch_row(pRes))//获取具体的数据
-
{
-
for(i=0;i<j;i++)
-
{
-
printf("%s\t",sqlrow[i]);
-
}
-
printf("\n");
-
}
-
}
-
else
-
{
-
printf("query Failed.\n");
-
}
-
mysql_free_result(pRes);
-
mysql_close(&DbObj);
-
return 0;
-
}
-
编译
g++ -g -o mysqltest mysql_test.cpp -I/usr/local/mysql/include -L/usr/local/mysql/lib -lmysqlclient
-I指定包含头文件路径
-L指定lib库的路径
-l指定依赖库
3、设置环境变量
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib:/usr/local/mysql/lib
4、执行
[mysql@rhel87 ~]$ ./mysqltest
id name
1 aa
2 bb
OK.
阅读(1566) | 评论(0) | 转发(0) |