【问题标题】:Syntax Error with Insert using MS SQL ODBC使用 MS SQL ODBC 插入时出现语法错误
【发布时间】:2015-01-06 20:44:00
【问题描述】:

我正在尝试从使用 pyodbc 的 python 程序中使用 Microsoft ODBC 11 SQL Driver for Linux 插入 Microsoft SQL Server 数据库。 (这是一口) 所以我测试了连接、子查询,并在单独的查询中使用 dateadd。这些都有效,但是当我尝试将它们全部放在这个插入语句中时,我在倒数第二行的倒数第二行出现语法错误。我在这里错过了什么?

cursor.execute("INSERT INTO room_use_log VALUES ("+
       "(SELECT bldg_flr_spc_id FROM bldg_flr_spc WHERE rm_atl_nbr="+
         rooms[y]["Name"] +"),'t','f',dateadd(ms,"+
         str(int(str(r.get(rooms[y]["Name"]))[1:])) +", '1970-01-01'),"+
         " dateadd(ms,"+
         str(int(time.time())) +
         ", '1970-01-01')" #<----that one
        )

这是整个错误:

Traceback (most recent call last):
  File "DBGetRedis.py", line 59, in <module>
    ", '1970-01-01')"
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 11 for SQL Server]
[SQL Server]Incorrect syntax near ')'. (102) (SQLExecDirectW)")

【问题讨论】:

    标签: python sql-server pyodbc


    【解决方案1】:

    您的 INSERT 语句中似乎缺少右括号。字符串中的最后一个括号是关闭 dateadd,您仍然需要另一个来关闭 VALUES 部分。试试:

    cursor.execute("INSERT INTO room_use_log VALUES ("+
       "(SELECT bldg_flr_spc_id FROM bldg_flr_spc WHERE rm_atl_nbr='"+
         rooms[y]["Name"] +"'),'t','f',dateadd(ms,"+
         str(int(str(r.get(rooms[y]["Name"]))[1:])) +", '1970-01-01'),"+
         " dateadd(ms,"+
         str(int(time.time())) +
         ", '1970-01-01'))" #<----that one
        )
    

    编辑:添加了以下评论中提到的单引号以修复该语句。

    【讨论】:

    • 是的...我正在配对括号,但引号中的那些很难检查。我的陈述中还有一个错误,请提及以获得支持。在 where 子句的等号后和另一边添加一个“'”。
    • 还有一件事要考虑:使用绑定参数是避免 SQL 注入等问题的更好做法。文档在这里:code.google.com/p/pyodbc/wiki/Cursor 但是对于一个简短的示例,您可以运行您的选择,将其抓取到变量中,然后执行如下语句: cursor.execute("INSERT INTO room_use_log (thisroom, thatroom, otherroom) VALUES (?, ?, ?)", pyv_thisroom, pyv_thatroom, pyv_otherroom)") 其中以 pyv* 开头的任何内容都是选择中的 Python 变量。抱歉语法错误,目前睡眠不足!
    猜你喜欢
    • 1970-01-01
    • 2018-09-04
    • 2012-04-08
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多