python RuntimeError:找不到替换“mi”

时间:2017-03-17 09:26:03

标签: python

我正在尝试将日期写入oracle DB

sql = """INSERT INTO app_mobile_scout
    (type_event, date_event, version_app, UUID, name_event, description, device_model, IMEI, ip_device).
    values ('%s', to_date('%s', "yyyy/mm/dd hh24:mi:ss"), '%s', '%s', '%s', '%s', '%s', '%s', '%s')"""%(type_event, date_event, version_app, UUID, name_event, description, device_mod
    res = cur.execute(sql)

我有一个错误:

RuntimeError: "mi" not found for replace in "INSERT INTO app_mobile
    (type_event, date_event, version_app, UUID, name_event, description, device_model, IMEI, ip_device).
    values ('2', to_date('2017/03/16 11:46:06', "yyyy/mm/dd hh24:mi:ss"), '4.0.4',......

我做错了什么?

2 个答案:

答案 0 :(得分:1)

与Python不同,Oracle DB不会像单引号'那样解释单引号"

在您的情况下,日期格式是在双引号之间写的,这是错误的。

换句话说,改变: [...], to_date('2017/03/16 11:46:06', "yyyy/mm/dd hh24:mi:ss"), [...] [...], to_date('2017/03/16 11:46:06', 'yyyy/mm/dd hh24:mi:ss'), [...]

关于Oracle DB中的单引号与双引号: https://community.oracle.com/message/3853568#3853568

答案 1 :(得分:1)

首先,在SQL中你应该use single quotes for strings. Double quotes are for identifiers

values ('%s', to_date('%s', 'yyyy/mm/dd hh24:mi:ss')
#                           ^                     ^

您的代码也是prone to SQL injection。而是Bind variables

# Note: Doesn't work yet.
cursor.execute("""
    INSERT INTO app_mobile_scout (
        type_event, 
        date_event, 
        version_app, 
        -- etc
    ) VALUES (
        :type,     -- <-- use the variable 'type' here.
        to_date(:date, 'YYYY/MM/DD HH24:MI:SS'),
        :version,
        -- etc
    );
""", {
    'type': type_event,    # <-- bind `type_event` to the variable 'type'
    'date': date_event,
    'version': version,
    # etc.
})

现在,由于某种未知原因,Oracle数据库将字符串中的:MI:SS解释为占位符,从而导致OP看到错误。我认为这是Oracle方面的一个错误。正如OP所证实的那样,似乎可以通过&#34;逃避&#34;通过加倍结肠

        to_date(:date, 'YYYY/MM/DD HH24::MI::SS'),