c 获取数据库数据计算机,使用c从单板计算机写入mysql数据库使用c

您需要在系统上安装第一的libmysqlclient-dev软件包(我假设你在linux下),那么你可以修改这个代码,以满足您的需要:

#include

#include

#include

#include

#include

#define BUFFER_SIZE 1024 // Increase this buffer if yoy want

/* This function is used for the database connection */

MYSQL * my_mysql_connection(const char *server, const char *db, const char *user, const char *pwd)

{

MYSQL *myh;

/* Some initialisation */

if (NULL == (myh = mysql_init(NULL)))

{

fprintf(stdeee, "Fails to allocate memory for MYSQL!\n");

exit (EXIT_FAILURE);

}

/* Connect to the database. */

if (NULL == mysql_real_connect (myh, server, user, pwd, db, 0, NULL, 0))

{

fprintf(stderr, "%s", mysql_error(myh));

free (myh);

return NULL;

}

return myh;

}

/* This function is used to perform a query */

int my_mysql_query(MYSQL *myh, const char *query)

{

/* Do the query request */

if (0 != mysql_query(myh, query))

{

fprintf(stderr, "FAIL to perform the query : '%s' %s\n", query, mysql_error(myh));

exit (EXIT_FAILURE);

}

return 0;

}

/*

* Suppose that your table students_table has this fields : student_number, student_name,

* student_address, student_phone

*/

/* This function is used to get and process the result of the query */

void my_mysql_process_query_result(MYSQL * myh)

{

int num_fields;

int i;

MYSQL_RES *query_result;

MYSQL_FIELD *field;

MYSQL_ROW row;

char *buffer;

buffer = (char *) calloc(BUFFER_SIZE, sizeof(char));

/* Select all students present in the students_table */

if (my_mysql_query(myh, "SELECT student_number, student_name, student_address, student_phone FROM students_table"))

{

exit (EXIT_FAILURE);

}

query_result = mysql_store_result (myh);

/* Retreive the number of rows and fields */

field = mysql_fetch_fields(query_result);

num_fields = mysql_num_fields(query_result);

/* construct the buffer containing each row */

while ((row = mysql_fetch_row (query_result)))

{

/* Init our buffer with fields sperated by ";", modify if you need, it's just an example */

memset(buffer, '\0', sizeof*buffer);

for (i = 0; i < num_fields - 1; i++)

{

strncat(buffer, row[i], strlen(row[i]) + 1);

strncat(buffer, ";", 2);

}

strncat(buffer, row[i], strlen(row[i]) + 1);

strncat(buffer, "\n", 2);

// You can process your buffer (row) here

process_student_row(buffer);

}

free(buffer);

mysql_free_result (query_result);

}

不要忘了链接到mysqlclient库:-lmysqlclient。

编辑:

您可以在Debian安装的libmysqlclient-DEV(http://packages.debian.org/squeeze/libmysqlclient-dev)是这样的:

sudo apt-get update

sudo apt-get install libmysqlclient-dev

您可以编译你的程序是这样的:

gcc -Wall my_msql_program.c -o my_mysql_program -lmysqlclient

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值