linux下c访问mysql数据库,并把数据提取打印出来,调试成功
源码:
#include <stdio.h>
#include <mysql/mysql.h>
#include <sys/types.h>
MYSQL mysql;
MYSQL_RES *res;
MYSQL_ROW row;
int main(void)
{
int result,col,i;
char *query="select * from name";
mysql_init(&mysql);
if (!mysql_real_connect(&mysql,"localhost","root","sc01","test",0,NULL,0))
{
fprintf(stderr, "Failed to connect to database: Error: %s\n", mysql_error(&mysql));
}else{
printf("yeah! it's ok!\n");
result=mysql_real_query(&mysql,query,strlen(query));
if(result==0)
{
printf("mysql sql=%s is succes ",query);
res=mysql_store_result(&mysql);
if(res)
{
printf("retived %lu Rows ",(unsigned long)mysql_num_rows(res));
col=mysql_num_fields(res);
while((row=mysql_fetch_row(res)))
{
for(i=0;i<col;i++)
{
printf("%s ",row);
printf(" ");
}
printf(" ");
}
mysql_free_result(res);
mysql_close(&mysql);
return 0;
}
else
{
printf("mysql result %s ",mysql_error(&mysql));
goto error;
}
}
}
error:
printf("error.... ");
return -1;
}
感觉用c访问数据库,爽!!!哈哈,可能是第一次用C写访问MYSQL数据库,而且还在linux下,还得继续努力,呵呵