我想做的是每分钟运行一个程序。该程序使用C代码获取当前时间和日期,然后我尝试获取一个MySQL查询,以比较数据库字段中的时间,看看它是否与当前时间匹配。我似乎无法使MySQL查询正常工作。
注意:代码中的%s用于C程序插入由c代码生成的当前时间。
下面是MySQL:
SELECT active, type, date, time, action, command FROM `Alarm`
WHERE TIME_FORMAT('time', '%H:%i') = '%s'WHen我在snprintf尝试插入时间变量后打印查询我得到的输出结果似乎是试图将值插入%i而不是%s,并且时间的格式不起作用:
SELECT alarm_active,alarm_category,alarm_date,alarm_time,alarm_action,alarm_command FROM Alarm WHERE TIME_FORMAT(alarm_time,'%H:6297664') = '<�F‘
下面是C代码:
char buffer[1024];
const char *query = "SELECT alarm_active, alarm_category, alarm_date, alarm_time, alarm_action, alarm_command FROM `Alarm` WHERE (alarm_time='%s')";
//const char *query = "SELECT active, type, date, time, action, command FROM `Alarm` WHERE active = '1'";
//Checking to see if connection to DB is succefful
if (mysql_query(conn, query) != 0)
{
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
} else {
if (snprintf(buffer, sizeof(buffer), query, current_time) >= sizeof(buffer))
{
printf("Issue with Buffer \n");
exit (-1);
}获取时间的其余代码:
char current_time [11];
time_t raw;
time(&raw);
struct tm *time_ptr;
time_ptr = localtime(&raw);
now with the "tm", you can format it to a buffer
char current_date[11];
char current_time [11];
strftime(current_date, sizeof(current_date), "%m/%d/%Y", time_ptr);
strftime(current_time, sizeof(current_time), "%H:%M", time_ptr);发布于 2017-01-28 07:10:30
为此,您不需要C代码。您可以在数据库中执行所有操作:
SELECT active, type, date, time, action, command
FROM `Alarm`
WHERE TIME_FORMAT(time, '%H:%i') = TIME_FORMAT(now(), '%H:%i') and
date = curdate();但是,我强烈建议您不要采用这种方法。您应该存储最后处理的记录的id (或者至少是日期/时间)。然后,您应该选择从那时起的所有ids。
你建议的方法很有可能在一分钟内运行两次,或者错过一分钟。
发布于 2017-01-28 07:17:16
TIME_FORMAT('time', '%H:%i')将time列的名称放在单引号中,单引号是字符串文字分隔符,而不是标识符分隔符。因此,您正在尝试从文本字符串' time‘格式化时间,而不是名为time的列的值。
试试这个:
TIME_FORMAT(`time`, '%H:%i')您可能想要阅读When to use single quotes, double quotes, and backticks in MySQL和https://dev.mysql.com/doc/refman/5.7/en/identifiers.html
另一个考虑因素。您说您正在使用C代码,我看到您有%s,我认为它是sprintf()的控制字符。在向SQL查询内插值之后,您应该检查该SQL查询。在MySQL命令行客户端或MySQL工作台中测试该查询。
或者更好的是,不要使用sprintf(),使用参数化查询。有关在C中使用参数化查询的示例,请参见http://lgallardo.com/en/2011/06/23/sentencias-preparadas-de-mysql-en-c-ejemplo-completo/。
发布于 2017-01-31 06:54:30
sprintf ... '%%H:%%i' ... %s也就是说,在sprintf中隐藏%H和%i,说明它们是字面百分比,而不是替换位置。在C代码中仅替换%s。当它到达MySQL时,它将是这个字符串:
... TIME_FORMAT(`time`, '%H:%i') = '12:34'https://stackoverflow.com/questions/41904422
复制相似问题