mysql c API访问数据库
#include <winsock2.h>
#include "CMySQL.h"
#include "stdio.h"
#define MYSQL_PORT 3306
void process_result_set(MYSQL mysql, MYSQL_RES *result);
void exit(MYSQL mydata,char *ep);
int main(int argc, char * argv[]) {
MYSQL mydata;
Database_Param p;
char queryName[600];
MYSQL_RES *result=NULL;
int status =0;
//初始化
strcpy(p.host,"127.0.0.1");
strcpy(p.user,"root");
strcpy(p.password,"root");
strcpy(p.db,"im");
p.port = MYSQL_PORT;
//初始化数据结构
if(mysql_init(&mydata) == NULL)
{
printf("init mysql data stauct fail\n");
system("pause");
return -1;
}
//连接数据库
if(argc == 1)
{
if(NULL == mysql_real_connect(&mydata,p.host,p.user,p.password,
p.db,p.port,NULL,CLIENT_MULTI_STATEMENTS))
{
printf("connect database fail,%s\n",mysql_error(&mydata));
system("pause");
return -1;
}
}
else
{
printf("run parameter error\n");
system("pause");
return -1;
}
//首先设置字符集
strcpy(queryName,"set names gbkd");
if(mysql_query(&mydata,"set names gbk")!=0)
{
exit(mydata,"set names fail");
return -1;
}
//查询数据(支持单个字段和多个字段,输出排版)
strcpy(queryName,"show databases");
if(mysql_query(&mydata,queryName) != 0)
{
exit(mydata,"execute sql syntax fail");
return -1;
}
//取得查询结果
result= mysql_store_result(&mydata);
process_result_set(mydata,result);
//处理多条插入语句,在mysql_real_connect(......)函数里的最后一个参数更改为:CLIENT_MULTI_STATEMENTS
strcpy(queryName,"insert into fangl.admin(username,password) values('fangl1','fangl1'),('fangl2','fangl2'),('fangl3','fangl3');\
insert into fangl.admin(username,password) values('fl1','fl1'),('fl2','fl2'),('fl3','fl3');\
insert into fangl.admin(username,password) values('fal1','fal1'),('fal2','fal2'),('fal3','fal3');\
select * from fangl.admin");
if(mysql_query(&mydata,queryName)!=0)
{
exit(mydata,"insert values fail");
return -1;
}
do {
/* did current statement return data? */
result = mysql_store_result(&mydata);
if (result)
{
/* yes; process rows and free the result set */
process_result_set(mydata, result);
mysql_free_result(result);
}
else /* no result set or error */
{
if (mysql_field_count(&mydata) == 0)
{
printf("%lld rows affected\n",
mysql_affected_rows(&mydata));
}
else /* some error occurred */
{
printf("Could not ret
相关新闻>>
- 发表评论
-
- 最新评论 更多>>