如何在Python中处理长SQL语句字符串

时间:2012-05-28 15:39:02

标签: python sql

我正在尝试使用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 Client而不是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)

2 个答案:

答案 0 :(得分:21)

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

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 /添加更多WHERE子句)然后是分支机构等。)

答案 1 :(得分:6)

where关键字前加一个空格。使用\时,Python不会添加空格:

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

要补充Martijn Pieters的答案,如果你使用三重引号字符串,你必须删除\,使用两者都不会得到换行符:

In [6]: """a\
b"""
Out[6]: 'ab'