mysql_query和通过sprintf()在其中插入变量的问题

时间:2019-03-29 20:39:29

标签: mysql sql c

我正尝试使用sprintf将变量DS18B20读取的温度值插入mysql数据库中,并将变量存储在字符串中,并将mysql_query写入数据库中。在数据库中,我有两列“ temp”和“ date”,它们是int和string数据类型。

在我以前的数据库中,一切工作正常,但是在此我遇到了一些问题。

列中的默认数据不为空

结果是我在终端中看到温度和日期,但是

SELECT * FROM tmpdate1 

给我“空集”

请帮助我找出问题所在并解决

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "libfahw.h"
#include <mysql.h>
#include <unistd.h>
#include <time.h>
#define BUF_SIZE                    (64)

int main(int argc, char ** argv)
{
        time_t t;
        char times[1024]={};
        char  timestr[] = {"%s"};
        time(&t);
        MYSQL *conn;
        char query[1024]={};
        char query1[1024]={};
        char query_str[] = {"INSERT INTO tmpdate1(temp) VALUES (%d)"};
        char query_str1[] = {"INSERT INTO tmpdate1(date) VALUES (%s)"};
        if ((conn=mysql_init(NULL))==NULL)
        {
           fprintf(stderr, "Could not init DB\n");
           return EXIT_FAILURE;
        }
       char temperature[BUF_SIZE];
       memset(temperature, 0, BUF_SIZE);

       if(mysql_real_connect(conn, "localhost", "user12", "34klq*", "defense3", 0, NULL, 0) == NULL)
       {
          fprintf(stderr, "DB connection error\n");
          return EXIT_FAILURE;
       }
      for (int i = 1; i>0; i++)
 {
                printf("\n %d", atoi(temperature)/1000);
                printf("\n %s", ctime(&t));
                sprintf(times, timestr, ctime(&t));
                sprintf(query, query_str, atoi(temperature)/1000);
                sprintf(query1, query_str1, timestr);
                mysql_query(conn, query);
                mysql_query(conn, query1);
   }
   return 0;
}

0 个答案:

没有答案
相关问题