无法使用'read_sql'来调用SQL查询类。

问题描述 投票:0回答:1

我试图用以下代码从数据库中提取结果。

import pandas as pd
import pyodbc

class DataManagement(object):

    def __init__(self, database = None, server=None, trusted_connection=True, database_driver=ODBC_SQL2005_2012, uid=None, pwd=None):
        self.server = server
        self.database = database
        self.uid = uid
        self.pwd = pwd


        # Use default server name none supplied - assumed to be localhost
        if self.server is None:
            self.server = SERVER

        if self.database is None:
            self.database = DATABASE

        # Use default sql credentials if none provided
        if self.uid is None or self.pwd is None:
            self.uid = DEFAULT_UID
            self.pwd = DEFAULT_PASSWORD

        if trusted_connection:
            self.connectionstring = "DRIVER={0};SERVER={1};DATABASE={2};Trusted_Connection=yes;".format(database_driver, self.server, self.database)
        else:
            self.connectionstring = 'DRIVER={0};SERVER={1};DATABASE={2};UID={3};PWD={4};'.format(database_driver, self.server, self.database, uid, pwd)

        self.connection = pyodbc.connect(self.connectionstring)

        self.cursor = self.connection.cursor()

    def __enter__(self):
        return self

    def __exit__(self, ctx_type, ctx_value, ctx_traceback):
        self.connection.commit()
        self.connection.close()

qq = DataManagement()
sql =("select * from ***** ")
data_df = pd.read_sql(sql, qq)

我得到一个错误。

Traceback (most recent call last):

  File "<ipython-input-94-453876631fe0>", line 3, in <module>
    data_df = pd.read_sql(sql, qq)

  File "***\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 380, in read_sql
    chunksize=chunksize)

  File "***\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 1468, in read_query
    cursor = self.execute(*args)

  File "***\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\sql.py", line 1426, in execute
    cur = self.con.cursor()

TypeError: 'pyodbc.Cursor' object is not callable

我看到一个类似的问题 TypeError: 'pyodbc.Cursor' 对象不可调用 (Python 3.6) 但无法从那里得到答案。

请帮助我。

sql python-3.x pandas pyodbc
1个回答
0
投票

我通过编辑下面的类来实现它的工作。

self.cursor = self.connection.cursor()

变成

self.cursor = self.connection.cursor
© www.soinside.com 2019 - 2024. All rights reserved.