Sql server 在python 3.2.5 onm win 7的pyodbc中从cursor.execute运行SQL查询时出错

Sql server 在python 3.2.5 onm win 7的pyodbc中从cursor.execute运行SQL查询时出错,sql-server,sql-server-2008,python-3.x,windows-7,pyodbc,Sql Server,Sql Server 2008,Python 3.x,Windows 7,Pyodbc,我正在Eclipse(4.3.2v20140221-1852)中与Win7上的PyDev一起使用pyodbc。我的python是3.2.5 我的代码是: cursor.execute("select top " + str(1) + " a.my_id, a.mycode" + "from my_table as a where a.mycode = ?", aGivenCode) 我有一个错误: pyodbc.ProgrammingError: ('4200

我正在Eclipse(4.3.2v20140221-1852)中与Win7上的PyDev一起使用pyodbc。我的python是3.2.5

我的代码是:

 cursor.execute("select top " + str(1) + " a.my_id, a.mycode" + 
               "from my_table as a where a.mycode = ?", aGivenCode)
我有一个错误:

pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver]
[SQL Server]Incorrect syntax near the keyword 'as'. (156) (SQLExecDirectW)")
为什么我在“作为一个”时出错


谢谢

试试这个?我想你错过了一个空间:

cursor.execute("select top " + str(1) + " a.my_id, a.mycode from my_table as a where a.mycode = ?", aGivenCode)
看到“a.mycode”和“from my_table”之间没有空格了吗?我不是百分之百确定那是对的,但是试试看

这些东西也更容易调试,如下所示:

sql = "select top " + str(1) + " a.my_id, a.mycode from my_table as a where a.mycode = ?"
print sql
cursor.execute(sql, aGivenCode)

对未来发展的几点建议:

  • 使用多行字符串表示法
    “”“
    可以更好地识别语法错误(如原始查询中列和表之间缺少空格)

  • 使用
    TOP
    值的参数,而不是字符串串联。该值必须用括号括起来

  • 根据这些准则,您的原始代码将更新为:

    top = 1
    cursor.execute("""select top (?) a.my_id, a.mycode
                      from my_table as a
                      where a.mycode = ?""",
                   (top, aGivenCode))