【问题标题】:How to fix a pyodbc connection, make a query and read as pandas Dataframe如何修复 pyodbc 连接,进行查询并读取为 pandas Dataframe
【发布时间】:2019-10-01 13:09:48
【问题描述】:

我正在尝试通过pd.read_sql(sql, db_connection_dw)查询

连接正常,如下:

driver= '{Devart ODBC Driver for ASE}'
server='---' 
db_environment='----'
username='----'
password='----'
port='----'
connectionString = 
('DRIVER='+driver+';SERVER='+server+';PORT='+port+';UID='+username+';PWD='+ 
password + ';DATABASE='+db_environment)
try:
    db_connection_dw = pyodbc.connect(connectionString)
except:
    print('could not connect')
    exit(0)

查询如下,很简单,返回前10个寄存器:

sql = """SELECT TOP 10 VariableID, 
            PatientID, 
            CONVERT(VARCHAR(10), ValueTime, 23) as ValueTime 
     FROM PV_VariableValues 
     WHERE VariableID = 15002262 and NumValue = 12 and YEAR(ValueTime) = 2019 and 
     MONTH(ValueTime) = 7
     """

使用pd.read_sql(sql, db_connection_dw)后返回如下Dataframe:

    VariableID  PatientID   ValueTime
0   15002262    9811        2019-07-02
1   15002262    9811        2019-07-02
2   15002262    9811        2019-07-03
3   15002262    9811        2019-07-03
4   15002262    9811        2019-07-03
5   15002262    9811        2019-07-03
6   15002262    9811        2019-07-04
7   15002262    9811        2019-07-04
8   15002262    9811        2019-07-04
9   15002262    9922        2019-07-25

当我进行更大的查询时出现问题,比如说 TOP 1000。 运行代码后返回以下错误:

Error: ('HY000', '[HY000] [Devart][ODBC][Adaptive Server Enterprise]Error on data reading from the connection:\r\nSe produjo un error durante el intento de conexión ya que la parte conectada no respondió adecuadamente tras un periodo de tiempo, o bien se produjo un error en la conexión establecida ya que el host conectado no ha podido responder.\r\nSocket Error Code: 10060($274C) (0) (SQLFetch)')

我尝试的另一种方法是在声明 sql 字符串后通过 chunksize 参数读取:

for chunk in pd.read_sql(sql, db_connection_dw, chunksize=10):
    print(chunk)

但是在一些打印之后它会停止并返回相同的错误。

有什么想法吗?

感谢您的提前

【问题讨论】:

    标签: python pandas odbc pyodbc devart


    【解决方案1】:

    由于您要连接到 sybase 数据库,请尝试更改此部分:

    driver ='{Adaptive Server Enterprise}'
    

    确保已安装驱动程序。要从 python 检查 ODBC 已安装驱动程序的列表,请运行以下代码:

    import pyodbc
    
    pyodbc.drivers()
    

    如果已安装,您应该会看到驱动程序名称'{Adaptive Server Enterprise}'。

    【讨论】:

    • 你是说这个? sap.com/cmp/syb/crm-xu15-int-asewindm/…,但这不是免费的!并且需要超过 2 GB 的压缩空间
    • 安装驱动程序“{Adaptive Server Enterprise}”后,问题依旧
    • 你的python版本和驱动的版本一样吗?也就是说,它们都是 32/64 位的吗?我以前发现这是导致问题的问题之一
    • 似乎使用驱动程序'{Adaptive Server Enterprise}'并按照以下步骤infocenter.sybase.com/help/index.jsp?topic=/…问题解决了
    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 2020-01-11
    相关资源
    最近更新 更多