【问题标题】:Is there a way with pandas to use read_sql() with an sql-statement, that takes multiple variables?pandas 有没有办法将 read_sql() 与 sql-statement 一起使用,它需要多个变量?
【发布时间】:2020-04-10 21:26:45
【问题描述】:

这是我的代码的一部分。我已经有一个包含值的数据库,并且需要根据该数据框中的值创建一个新的数据框(目前这些值只有 12 和 13,存储在 header_row_ids 变量中)。

当我运行脚本时,我收到以下错误消息:

pandas.io.sql.DatabaseError: 执行失败 sql 'SELECT * FROM dbo.TestDetails WHERE Id IN (?,?), (13, 12)': ('07002', '[07002] [Microsoft] [ODBC SQL Server 驱动程序]COUNT 字段不正确或语法错误')

有人可以帮我解决这个问题吗?我将不胜感激。

import pypyodbc
import pandas

sourceConnection = pypyodbc.connect(
            self.sourceDriver +
            self.sourceServer +
            self.sourceDatabase
            )

placeholders = ",".join("?" * (len(self.header_row_ids)))
sql_source_detail_select = "SELECT * FROM dbo.TestDetails WHERE Id IN (%s)" % placeholders

header_row_ids = [12, 13]
header_row_ids_string = str(self.header_row_ids).strip('[]')

new_sql_source_detail_select = sql_source_detail_select + ", (" + header_row_ids_string + ")"

dataframe = pandas.read_sql(new_sql_source_detail_select, sourceConnection)

【问题讨论】:

  • Warning:新的.format() 方法旨在替换旧的% 格式语法。后者已被淡化,(但尚未正式弃用)。

标签: python sql pandas pyodbc pypyodbc


【解决方案1】:

read_sql 接受一个 params 参数,您可以使用它来传递参数值:

# header_row_ids = [12, 13]
# sql = "SELECT * FROM dbo.TestDetails WHERE Id IN (?,?)"

dataframe = pandas.read_sql(sql, sourceConnection, params=header_row_ids)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 2021-05-02
    • 2018-03-15
    • 2016-11-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    相关资源
    最近更新 更多