将 ILIKE 与 Python 中的参数与 pd.read_sql 和 psycopg2 一起使用

Using ILIKE with parameters in Python with pd.read_sql and psycopg2

此查询 运行s 在 SQL(PostgreSQL 数据库)中没有问题:

SELECT 

number_column
                
FROM 

number_table

WHERE 

number_column ILIKE ANY (array[     '%57244048699%',
                                    '%150310003808%',
                                    '%290030480768%',
                                    '%290070002130%',
                                    '%290100059345%',]

我正在尝试将其翻译成 Python,如下所示:


numbers = ['%57244048699%',
           '%150310003808%',
           '%290030480768%',
           '%290070002130%',
           '%290100059345%',]

sql_query = """

          SELECT 

number_column
                
FROM 

number_table

WHERE 

number_column ILIKE ANY (array[%(numbers)s]

            """
df = pd.read_sql(sql_query, engine, params = {'numbers':tuple(numbers)})

但是,我收到以下错误:

(psycopg2.errors.UndefinedFunction) operator does not exist: character varying ~~* record
LINE 19:                 where number ilike any (array[('%...
                                                 ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

有谁知道如何在 Python 中实现上述查询 运行?

谢谢!

使用这个:

import psycopg2

#establishing the connection
conn = psycopg2.connect(
   database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)

#Setting auto commit false
conn.autocommit = True

#Creating a cursor object using the cursor() method
cursor = conn.cursor()
numbers = ['%57244048699%',
               '%150310003808%',
               '%290030480768%',
               '%290070002130%',
               '%290100059345%',]
number_tuple=tuple(numbers)
sql_query = "SELECT number_column           
FROM 
number_table
WHERE 
number_column ILIKE ANY {}".format(number_tuple)
    
cursor.execute(sql_query )

根据 psycopg2 文档 List adaption 列表适用于数组。所以你把事情复杂化了。

尝试:

number_column ILIKE ANY (%(numbers)s)

和参数:

{'numbers': numbers}