【问题标题】:panda.to_sql to call stored procedure with parameters via mysql.connectorpanda.to_sql 通过 mysql.connector 调用带参数的存储过程
【发布时间】:2020-03-12 20:06:33
【问题描述】:

我有一些 Connection 类,它有 __enter____exit__ 方法来返回 mysql.connector.MySQLConnection 实例。

需要的是运行mysql存储过程并获取数据作为数据框。 我尝试了很多方法:?、%s、:1、%(name)s 并将列表、元组、字典传递给参数。

with Connection(**self._connection) as conn:
   df = pandas.read_sql("call stored_procedure (?);", conn, params=['test'])

我阅读了Pandas read_sql with parametersMySQL Stored Procedures, Pandas, and "Use multi=True when executing multiple statements" 和其他一些内容,但仍然找不到解决方案,因为它总是以 “并非所有参数都在 SQL 语句中使用” 或要求使用多=真;

当然我们可以用游标读取数据,获取它并传递给 DataFrame 构造函数,但是根据文档必须有一种使用 pandas.read_sql 的方法。

【问题讨论】:

  • 你调用了你的存储过程,但你需要实际选择数据,select语句在哪里?
  • 你是说不能通过read_sql调用SP?
  • 我假设 proc 返回一个结果集。 SQL 中是否还有其他返回行/值的语句
  • 再次仔细阅读pandas.pydata.org/pandas-docs/version/0.20.3/generated/…,我停在了以下短语:sql : string SQL query or SQLAlchemy Selectable (select or text object) 这可能意味着你可以' t 在 read_sql 中调用 sp。
  • 一个存储过程不是一张表或一个数据样本,它是一系列你执行的SQL语句,你需要的是过程的输出,一个dim/fact/stage/temp某种表。你需要选择它。

标签: python mysql pandas read-sql


【解决方案1】:

总结:不能这样带参数调用SP 证明:Pandas Docs

【讨论】:

    【解决方案2】:

    odbc / SQL Server 可以。也许您可以调整对 mysql 的调用。基本上,只需附加您的参数:

    # imports for SQL data part
    import pyodbc
    import pandas as pd
    
    # Get connected
    
    strconnODBC = ("Driver={SQL Server Native Client 11.0};"
                "Server=SERVERNAME;"
                "Database=DATABASENAME;"
                "Trusted_Connection=Yes")       # You may need to enter Login-info
    
    cnn = pyodbc.connect(strconnODBC)
    
    
    # Call a SQL Server Stored Procedure with Parameters
    strMyPara='ShowMeResults'
    strSQL="[dbo].[q_Your_SP] "
    strSQL= strSQL + " @WhatYouWant='" + strMyPara + "'"
    
    data = pd.read_sql(strSQL , cnn)  
    print('Max of ' + strMyPara + ': ' + str(data['Result'].max()))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-08
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多