2017-03-17 93 views
1

我想写一个日期到Oracle DB蟒蛇RuntimeError: “MI” 没有找到替代

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',...... 

我在做什么错?

+0

您可以不使用字符串格式化来创建你的SQL语句开始进行工作,各地。它会打开你的SQL注入攻击。这不是什么常见问题,但它显示了你应该做什么:https://wiki.python.org/moin/DbApiFaq。另外,有些数据库对待引用的方式与Python不同,Oracle看起来就是其中之一。 – jszakmeister

回答

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 injectionBind 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,似乎可以用“逃离”结肠加倍它

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

RuntimeError:在“INSERT INTO app_mobile (type_event,date_event,version_app,UUID,name_event,description,device_model,IMEI,ip_device)”中找不到替换项“MI” values(:type_event,to_date(:date_event,'YYYY/MM/DD HH24:MI:SS'),:version_app,:UUID,:name_event,:description,:device_model,:IMEI,:ip_device)“。必须是['version_app','date_event','IMEI','UUID','device_model','description','ip_device','name_event','type_event'] – Rainmaker

+1

@Rainmaker看起来像一个http问题://stackoverflow.com/questions/7342642/oracle-pl-sql-how-to-escape-colon-being-misinterpreted-for-bind-variable。我现在没有测试Oracle数据库,但是如果您尝试过'HH24 :: MI :: SS'或'HH24 \\:MI \\:SS',该怎么办? – kennytm

+0

双冒号很棒!谢谢! – Rainmaker

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数据库中单引号VS双引号: https://community.oracle.com/message/3853568#3853568

+0

我将它更改为to_date('2017/03/16 11:46:06','yyyy/mm/dd hh24:mi:ss'),但结果相同 – Rainmaker

+1

您是否可以在添加此新尝试后更新您的帖子+新的错误? – pltrdy

+0

同样的错误。绝对 – Rainmaker