18

我正在尝试使用 python 从 SQL 数据库中获取信息

当 SQL 语句很简单时,我能够连接和检索数据,例如

#cursor.execute("SELECT * FROM Client WHERE UsesTimesheet = 1 ORDER BY ClientName")

但是,当我转到更复杂的语句时,我收到如下所示的错误

Traceback (most recent call last):
 File "F:\Python\Test - AutoCad.py", line 30, in <module>
where jobnum = 1205992")
File "C:\Python26\ArcGIS10.0\lib\site-packages\pymssql.py", line 196, in execute
raise OperationalError, e[0]
OperationalError: SQL Server message 102, severity 15, state 1, line 1:
Incorrect syntax near 'jobnum'.

此语句在我使用 Microsoft SQL 2008 客户端时有效,但在 python 中无效。

我在做什么不正确?对于复杂的语句,我应该使用 SQLAlchemy 吗?

http://www.sqlalchemy.org/

当前代码如下

import pymssql
import _mssql
import sys

# Connect to db using Windows Integrated Authentication.
conn = _mssql.connect(server='000.000.0.0', database='Mydb', trusted=True)
conn = pymssql.connect(host='000.000.0.0', database='Mydb', trusted=True)

# prepare a cursor object using cursor() method
cursor = conn.cursor()

cursor.execute("""SELECT PJI.*, PJO.*,
        CST.ABCGS
FROM  dbo.Traverse AS TRE
              LEFT OUTER JOIN dbo.TraversePreEntry AS TPE
                    ON TRE.JobNum = dbo.GetJobNumberFromGroupId(TPE.GroupId)
              LEFT OUTER JOIN AutoCADProjectInformation AS PJI
                    ON TRE.JobNum = PJI.JobNumber
              LEFT OUTER JOIN CalculationStorageReplacement AS CST
                    ON CST.ProjectNumber = dbo.GetJobNumberFromGroupId(TPE.GroupId
              LEFT OUTER JOIN dbo.TraverseElevations AS TEV
                  ON TRE.TraverseId = TEV.TraverseId
              LEFT OUTER JOIN VGSDB.dbo.ProjectOffice AS PJO
                    ON PJI.PjbId = PJO.PjbId
where jobnum = 1205992""")

# Fetch rows
data = cursor.fetchall()

print "Info : %s " % str(data)
4

2 回答 2

31

where您的 python 字符串在没有换行符的情况下连接在一起,因此关键字之前没有空格。使用多行字符串文字时,最好使用三引号字符串:

cursor.execute("""\
SELECT PJI.*, PJO.*, 
        CST.ABCGS 
FROM  dbo.Traverse AS TRE 
              LEFT OUTER JOIN dbo.TraversePreEntry AS TPE 
                    ON TRE.JobNum = dbo.GetJobNumberFromGroupId(TPE.GroupId)
              LEFT OUTER JOIN AutoCADProjectInformation AS PJI
                    ON TRE.JobNum = PJI.JobNumber
              LEFT OUTER JOIN CalculationStorageReplacement AS CST
                    ON CST.ProjectNumber = dbo.GetJobNumberFromGroupId(TPE.GroupId)
              LEFT OUTER JOIN dbo.TraverseElevations AS TEV
                  ON TRE.TraverseId = TEV.TraverseId
              LEFT OUTER JOIN VGSDB.dbo.ProjectOffice PJO
                    ON PJI.PjbId = PJO.PjbId
where jobnum = 1205992""")

三引号字符串保持换行符:

>>> "one\
... two"
"onetwo"
>>> """one
... two"""
"one\ntwo"

如果这是您中的一个,则不一定需要使用 SQLAlchemy,但是随着项目的增长,您会发现该库提供了许多优势,包括使条件逻辑更容易(基于 if/then 分支添加更多 WHERE 子句, ETC)。

于 2012-05-28T15:46:02.170 回答
6

where在关键字之前放置一个空格。Python 在使用 \ 时不添加空格:

In [5]: print "a\
   ...: b"
ab

为了补充 Martijn Pieters 的答案,如果您使用三引号字符串,则必须删除\,同时使用两者都不会得到换行符:

In [6]: """a\
b"""
Out[6]: 'ab'
于 2012-05-28T15:44:38.877 回答