1
我在嘗試使用下面的代碼來查詢SQL Server 2012的數據庫:編程錯誤與pyodbc
import pyodbc
class sqlserverConnector:
def __init__(self, connectionString):
"""
this is a typical connection string using windows authentication and the DSN manager:
'DSN=python;Trusted_Connection=yes'
"""
self._conn = pyodbc.connect(connectionString)
self._curs = self._conn.cursor()
self.fetchall = self._curs.fetchall
self.description = self._curs.description
self.columns = dict()
def __del__(self):
self._conn.close()
def __iter__(self):
return self._curs.__iter__()
# executes SQL statements
def execute(self, statement, **params):
if params is None:
self._curs.execute(statement)
else:
self._curs.execute(statement,params)
# creates a dictionary of column names and positions
if self._curs.description != None:
self.columns = dict((field[0], pos) for pos, field in enumerate(self._curs.description))
else:
None
和:
from sqlutil import *
sqlcnxn = sqlserverConnector('DSN=python;Trusted_Connection=yes')
rows = sqlcnxn.execute("select * from demographics", params=None)
for row in rows:
print row
break
目標是打印出單行(表有80k +行)。不過我總是收到此錯誤信息:
pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000')
我身邊有一派,看起來這會彈出不同的人出於不同的原因,沒有我已經找到了解決方案,適合我的錯誤。我認爲發生的是execute
方法默認爲第一個else
聲明,而不是第一個if
聲明。
我不知道它總是創建一本字典。謝謝。一個後續問題,當我測試一個像你一樣的空字典時,建議行變爲None。爲什麼是這樣? – mnky9800n
@ mnky9800n:你的函數不返回任何東西;你忘了在最後迴歸自我。 –