在 C 项目上工作,我试图将值插入 mysql 数据库(beaglebone black 上的 linux debian)。当我将常量插入数据库时,代码工作正常,但我无法弄清楚如何获取日期/时间和 double (温度)的变量。已经进行了一个星期,但似乎无法弄清楚,所以任何见解都将不胜感激。
我尝试过的所有各种事情都以编译错误、数据库中的 null 或零结束。我想我已经很接近了……但显然遗漏了一些东西,可能是在 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]
关于mysql - c 将变量插入 mysql 数据库 beaglebone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29355180/