简体   繁体   中英

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? 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

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
  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 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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