c 将变量插入 mysql 数据库 beaglebone

c insert variable to mysql database beaglebone

在 C 项目上工作,我试图将值插入 mysql 数据库(linux debian on beaglebone black)。当我将常量插入数据库时​​,代码工作正常,但我无法弄清楚如何获取 date/time 和双数(温度)的变量。已经进行了一个星期,但似乎无法弄清楚,所以任何见解都将不胜感激。

我尝试过的所有各种事情都以编译错误结束,数据库中为空或为零。我想我很接近...但显然遗漏了一些东西,可能在 INSERT INTO 行中?

char buf[LEN];
time_t curtime;
struct tm *loc_time;

curtime = time (NULL);

loc_time = localtime (&curtime);


strftime (buf, LEN, "%Y-%m-%d" " " "%X", loc_time);
fputs (buf, stdout);


MYSQL *con = mysql_init(NULL);

if (con == NULL)
{
   fprintf(stderr, "mysql_init() failed\n");
   exit(1);
}

if (mysql_real_connect(con, "localhost", "user", "pass", "TempDB", 0, NULL, 0) == NULL) 
{
   finish_with_error(con);
}   

if (mysql_query(con, "CREATE TABLE IF NOT EXISTS TempMeas(MeasTime DATETIME, Temp DOUBLE)"))
{
    finish_with_error(con);
}

if (mysql_query(con, "INSERT INTO TempMeas(MeasTime, Temp) VALUES('%d', '%d')", buf, j))
{    
    finish_with_error(con);
}

mysql_close(con);

exit(0);

如果您想将实际日期和时间插入 SQL,您可以使用 sql:

INSERT INTO TempMeas(MeasTime, Temp) VALUES(now(), 'other value');

您可以通过以下方式获得其他值:

#include<string.h>      # needed for sizeof()

/* all the other stuff */

char query1[999];
int num = sprintf(query1, "INSERT INTO TempMeas(MeasTime, Temp) VALUES(now(), '%d');", j);
if (num > sizeof(query1))
{
  printf("Error: Query too long.\n");
  exit (1);
}
if (mysql_query(con, query1))
{
  printf("Error: mysql_query failed.");
  exit (1);
}

已更改 query 已定义大小,并检查实际查询是否适合我们的 char query[999]