【问题标题】:Passing parameters into a pd.read_sql_query将参数传递到 pd.read_sql_query
【发布时间】:2021-08-24 08:25:49
【问题描述】:

有这样的查询:

data_raw_sql = pd.read_sql_query('''SELECT a, Date, c                    
                                 FROM table_d 
                                 where a IN {0} 
                                 AND Date >= "2021-07-25" '''.format(my_tuple), conn
                                 )

我希望能够将日期作为变量传递。 如何创建 read_sql_query 以便我可以向其中传递多个变量,包括格式化元组和添加其他变量?

【问题讨论】:

  • 根据您的要求创建一个构建 sql 查询的函数,然后从 read_sql_query 中调用该函数,这样 SQL 查询就会在那里被替换。

标签: python sql pandas


【解决方案1】:

read_sql_query 的第一个参数应该是字符串或 SQLAlchemy Selectable (source)。在您的解决方案中,字符串分布在多行中,因此您应该使用triple quote syntax 来包装多行字符串。

这是你可以做的,如果你需要创建一堆这样的查询,你应该创建一个函数来为你做这件事。正如 Teja Goud 提到的那样。

#Define a, Date, c, t (the tuple) and format the query string as following
query = """SELECT {}, {}, {} FROM table_d WHERE a IN {} AND Date >= '2021-07-25'""".format(a, Date, c, t)

data_raw_sql = pd.read_sql_query(query, conn)

【讨论】:

    猜你喜欢
    • 2013-01-31
    • 2015-11-03
    • 2016-09-02
    • 2014-07-20
    • 2020-07-28
    • 2014-01-05
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多