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

我想从单板计算机读取网络数据包到数据库(确切地说是mysql),单板计算机和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 

如果mySQL在普通PC上运行,那么您需要在单板计算机和普通PC之间进行通信,以便将您希望的数据从板传输到PC。 你需要一台PC上的某种服务器。 完成后,PC然后获取数据并使用mySQL C API将其提交到mySQL数据库。

我可能错了,但你可能会在你头上。 一般的设计很简单,如果对你来说不明显,那可能是你想要做的事情太难了。