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

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

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) 但无法从那里得到答案。

请帮助我。

解决方案:

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

self.cursor = self.connection.cursor()

变成

self.cursor = self.connection.cursor

给TA打赏
共{{data.count}}人
人已打赏
未分类

DRF ListAPIView 自定义返回不是一个对象

2022-9-23 11:23:01

未分类

.

2022-9-23 11:33:38

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索