点击(此处)折叠或打开
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <mysql.h>
- /* int main(int argc, char* argv[]) {
- MYSQL mysql;
- MYSQL_RES *rs=NULL;
- MYSQL_ROW row;
- if (connect_mysql(&mysql)) {
- return 1;
- }
- if (getSection(&mysql)) {
- mysql_close(&mysql);
- return 1;
- }
- getChannelList(&mysql,&rs,1);
-
- while(row=mysql_fetch_row(rs))
- {
- printf("%d %d %d\n", atoi(row[0]),atoi(row[1]),atoi(row[2]));
- }
-
- mysql_free_result(rs);
- mysql_close(&mysql);
- return 0;
- }
- */
- /*connect mysql*/
- int connect_mysql(MYSQL* mysql) {
- printf("Initializing mysql.................");
- if (!mysql_init(mysql)) {
- return 1;
- }
- printf("Connectiong to mysql...............");
- if (!mysql_real_connect(mysql, "localhost", "root", "1qazXSW2", "temperature4001", 0, NULL,0)) {
- fprintf(stderr, "Error: %s\r\n", mysql_error(mysql));
- return 1;
- }
- //设置mysql连接的字符集
- mysql_query(mysql, "SET NAMES 'utf8'");
- return 0;
- }
- /*accept DISTINCT sectionID*/
- int getSection(MYSQL *mysql) {
- int ret, field_count, row_count, i;
- int *lengths;
- char *query = "select DISTINCT sectionID from baseinfo";
- MYSQL_RES *result;
- MYSQL_ROW row;
- ret = mysql_real_query(mysql, query, strlen(query));
- if (ret != 0) {
- printf("加载不了users的数据。\n");
- return 1;
- }
- result = mysql_store_result(mysql);
- row_count = (int) mysql_num_rows(result);
- field_count = (int) mysql_num_fields(result);
- // printf("the count is %d ,the field count %d\n",row_count,field_count);
- if (result == NULL && field_count == 0) {
- printf("无数据");
- return 1;
- }
- while(row = mysql_fetch_row(result))
- {
- printf("%d \n", atoi(row[0]));
- }
- // for (i = 0; i < row_count; i++) {
- // row = mysql_fetch_row(result);
- // printf("%d \n", atoi(row[0]));
- // }
- mysql_free_result(result);
- return 0;
- }
- /*获取函数*/
- int getChannelList(MYSQL *mysql,MYSQL_RES **result,int sectionID)
- {
- char sql[500];
- int ret;
-
- memset(sql,0x00,500);
- sprintf(sql,"select a.baseID,a.deviceID,a.channelID,b.param3,b.param2,b.param1,b.param0 from baseinfo a,baseParam b where a.baseID=b.baseID AND a.flag=1 AND a.sectionID=%d order by a.deviceID, a.channelID,a.baseID ;",sectionID);
- // printf("[INFO]: SQL is %s\n",sql);
-
- ret = mysql_real_query(mysql,sql, strlen(sql));
- if (ret != 0) {
- printf("exec sql %s error!\n",sql);
- return -1;
- }
- *result = mysql_store_result(mysql);
- return 0;
- }
- /*插入数据*/
- int insertTempData(MYSQL *mysql,int baseID,double temperature)
- {
- char sql[500];
-
- int ret;
-
- memset(sql,0x00,500);
-
- sprintf(sql,"INSERT INTO tempData(baseID,temperature) VALUES(%d,%f);",baseID,temperature);
-
- printf("[INFO]: SQL is %s\n",sql);
-
- ret = mysql_real_query(mysql,sql, strlen(sql));
- if (ret != 0) {
- printf("exec sql %s error!\n",sql);
- return -1;
- }
-
- return 0;
- }