#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include "mysql.h"
int main(int argc, char * argv[])
{
MYSQL my_connection;
MYSQL_RES * my_res;
MYSQL_ROW row;
MYSQL_FIELD * fields;
char str[30];
int res;
int i;
mysql_init(&my_connection);
if (mysql_real_connect(&my_connection, "192.168.1.30", "root", "mysql", "sun", 0, NULL, 0))
{
printf("connect succeed!\n");
/*
res = mysql_query(&my_connection, "insert into buddy(user_id, friend_id, nickname, signature)\
values(1001, 112233, 'kaka', 'god')");
*/
res = mysql_query(&my_connection, "select user.user_name, buddy.friend_id, buddy.nickname, buddy.signature\
from buddy join user on buddy.user_id = user.user_id where user_name = 'Robert' order by friend_id");
if (!res){
my_res = mysql_store_result(&my_connection);
//print colunm
int num_fields = mysql_num_fields(my_res);
fields = mysql_fetch_fields(my_res);
for (i = 0; i < num_fields; i++)
{
printf("%s ", fields[i].name);
}
printf("\n");
//print results
while ( (row = mysql_fetch_row(my_res)) != NULL)
{
int * lengths = mysql_fetch_lengths(my_res);
for (i = 0; i < num_fields; i++){
printf("%s ", row[i] ? row[i] : "NULL");
}
memset(str, 0, sizeof(str));
memcpy(str, row[2], strlen(row[2]));
printf("[in c variable: %s]", str);
printf("\n");
}
mysql_free_result(my_res);
}
else{
printf("search error\n");
}
mysql_close(&my_connection);
}
else
{
printf("fail to connect to mysql, error:%s\n", mysql_error(&my_connection));
}
return EXIT_SUCCESS;
}
c程序访问mysql数据库实例
最新推荐文章于 2023-11-12 22:58:27 发布
本文提供了一个使用C语言连接并查询MySQL数据库的例子。该程序通过连接到指定的数据库服务器,执行SQL查询来获取特定用户的朋友列表,并展示如何处理查询结果。
887

被折叠的 条评论
为什么被折叠?



