0

我在 C 中创建了带有混合数据的插入字符串,并且无法插入行。
如我所见,问题可能出在我的语言环境中使用逗号作为小数分隔符的浮点数中。

所以,插入时我收到错误消息:

错误:INSERT 的表达式多于目标列
第 1 行:...0:11:37.097203 +0100'、'关于解决问题的书'、''、'PCS'、0,000000)

插入代码:

 snprintf(sqlInsert, sizeof(sqlInsert), "INSERT INTO mytable (dtbl_id, kni, dtmp, iname, tagname, mea, klc) VALUES 
 (%d, '%s', '%s', '%s', '%s', '%s', %f)", o, k, dt, es, tagname, meas)), IL.klc);

如何解决这种情况以正确插入双精度数字?

4

1 回答 1

1
rc = snprintf(sqlInsert, sizeof sqlInsert
, "INSERT INTO mytable (dtbl_id, kni, dtmp, iname, tagname, mea, klc)"
" VALUES               (%d,     '%s', '%s', '%s',  '%s',   '%s', %f);"
                       , o,      k,    dt,   es, tagname, meas, IL.klc);

更新:如果存在语言环境问题, setlocale() 可能会帮助您在程序中设置本地。LC_ALL=POSIX(或 C)应始终存在。(很可能是其中一种 {%e %f %g} 格式对区域设置不敏感)

下面的程序演示了 setlocale() 的使用:

#include <stdio.h>
#include <locale.h>

#pragma DONT define DEFAULT_LOCALE "POSIX"
#define DEFAULT_LOCALE "nl_NL.utf8"
/* LC_NUMERIC LC_ALL */

int main(int argc, char **argv)
{
    double val;
    char *old, *new;

    val = 1024 * 1024;
    val /= 10;

    printf ("Original: Val=%f\n", val);
    new = argv[1] ? argv[1] : DEFAULT_LOCALE ;

    old = setlocale (LC_ALL, new );

    printf("Old=%s, New=%s\n", old, new );
    printf ("After change: Val=%f\n", val);

    new = setlocale (LC_ALL, old );

    printf("Old=%s, New=%s\n", new,  old);
    printf ("After restore: Val=%f\n", val);
return 0;
}

输出:

plasser@pisbak:./a.out
Original: Val=104857.600000
Old=nl_NL.utf8, New=nl_NL.utf8
After change: Val=104857,600000
Old=nl_NL.utf8, New=nl_NL.utf8
After restore: Val=104857,600000
plasser@pisbak:

阅读手册后,我希望 setlocale() 返回旧设置,但情况似乎并非如此。也许我无意中更改了一些全局设置:-[

更新:明确地将参数转换为 *printf() 函数总是好的。

#include <locale.h>
(void) setlocale (LC_NUMERIC, "POSIX" );

rc = snprintf(sqlInsert, sizeof sqlInsert
, "INSERT INTO mytable (dtbl_id, kni, dtmp, iname, tagname, mea, klc)"
" VALUES               (%d,   '%s', '%s', '%s',   '%s',  '%s', %f);"
                  , (int) o,     k,   dt,   es, tagname, meas, (double) IL.klc);
于 2012-03-03T12:52:13.013 回答