Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python pyodbc编程错误_Python_Sql_Pyodbc - Fatal编程技术网

Python pyodbc编程错误

Python pyodbc编程错误,python,sql,pyodbc,Python,Sql,Pyodbc,我正在尝试使用以下代码查询SQL Server 2012数据库: import pyodbc class sqlserverConnector: def __init__(self, connectionString): """ this is a typical connection string using windows authentication and the DSN manager: 'DSN=python;Tr

我正在尝试使用以下代码查询SQL Server 2012数据库:

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
以及:

目标是打印出一行(该表有80k+行)。但是,我总是收到以下错误消息:

pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000')

我在谷歌上搜索过,这似乎是出于不同的原因为不同的人弹出的,我发现没有一个解决方案适合我的错误。我认为现在发生的是
execute
方法默认为第一个
else
语句,而不是第一个
if
语句。

当您使用
**params
符号时,
params
总是字典

使用
params=None
调用该函数意味着您现在有了一个包含以下内容的字典:

>>> def func(**params):
...     print params
... 
>>> func()
{}
>>> func(params=None)
{'params': None}
>>> func(foo='bar')
{'foo': 'bar'}
该语法用于接受任意关键字参数,如上面的
foo
关键字参数所示

请删除
**
或测试空字典,并且在调用
时不要设置
参数=None
。execute()

以及:


请注意,
execute()
函数没有
return
语句,这意味着
rows
将被设置为
None
(函数的默认返回值)。如果要返回连接对象以便可以对其进行迭代,请添加
return self

我不知道它总是创建字典。非常感谢。接下来的一个问题是,当我测试一个空字典(如您推荐的行)时,它将变为“无”。这是为什么?@mnky9800n:您的函数不返回任何内容;最后你忘了
返回self
>>> def func(**params):
...     print params
... 
>>> func()
{}
>>> func(params=None)
{'params': None}
>>> func(foo='bar')
{'foo': 'bar'}
def execute(self, statement, **params):
    if not params:
        self._curs.execute(statement)
    else:
        self._curs.execute(statement, params)
    # ...
rows = sqlcnxn.execute("select * from demographics")