简体   繁体   English

如何使用 Teradata 将参数列表传递给 Pandas read_sql

[英]How to pass a list of parameter to Pandas read_sql with Teradata

Is there a way or how can I correct my syntax in order to pass a list of parameter of string into SQL query in pandas?有没有办法或如何纠正我的语法,以便将字符串参数列表传递到 Pandas 中的 SQL 查询中? I have the following code but it it not working So i have a list of string and I need to pass that list parameter dynamically into the query我有以下代码,但它不起作用所以我有一个字符串列表,我需要将该列表参数动态传递到查询中

import teradatasql
import pandas as pd 

connection = tearadatasql.connect(host="xxx",user="xxx",password="xxx")
column_list = ['A','B','C']

query = """
            select column, row
            from table1
            where column in (%s)
        """

df = pd.read_sql(query, connection, params=column_list)      

You should fill in the %s with some parameters你应该用一些参数填写 %s

df = psql.read_sql(('select "column","row" from "table1" '
                 'where "column" in %(col_list)s'), connection, params={'col_list':column_list})

You have a couple of issues:你有几个问题:

  1. The package name teradatasql is misspelled in your example tearadatasql.connect包名称teradatasql在你的榜样拼错tearadatasql.connect
  2. You must compose the IN-predicate with the same number of question-mark parameter markers as the number of values you intend to bind.您必须使用与要绑定的值的数量相同数量的问号参数标记来组成 IN 谓词。

In your example, you intend to bind the three values contained in the column_list variable, so you must compose the IN-predicate with three question-mark parameter markers.在您的示例中,您打算绑定column_list变量中包含的三个值,因此您必须用三个问号参数标记组成 IN 谓词。

Generally speaking, you should dynamically compose the IN-predicate with the number of question-mark parameter markers equal to the number of values in the parameter-value list that you will bind.一般来说,您应该动态地组合 IN 谓词,其中问号参数标记的数量等于您将绑定的参数值列表中的值的数量。

Below is a modified version of your example that corrects these two issues.下面是您的示例的修改版本,它更正了这两个问题。 I actually ran this example and verified that it works.我实际上运行了这个例子并验证了它的工作原理。

import teradatasql
import pandas as pd 
with teradatasql.connect(host="whomooz",user="guest",password="please") as connection:
  with connection.cursor() as cur:
    cur.execute("create volatile table table1 (c1 varchar(1), c2 integer) on commit preserve rows")
    cur.execute("insert into table1 values ('A', 1) ; insert into table1 values ('B', 2)")
  column_list = ['A','B','C']
  query = "select c1, c2 from table1 where c1 in ({}) order by c1".format(','.join(['?'] * len(column_list)))
  print(query)
  print("with params={}".format (column_list))
  df = pd.read_sql(query, connection, params=column_list)
  print(df)

This example produces the following output:此示例产生以下输出:

select c1, c2 from table1 where c1 in (?,?,?) order by c1
with params=['A', 'B', 'C']
  c1  c2
0  A   1
1  B   2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM