Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to Pass in Table Name for Query psycopg2

I am trying to pass in the table name for my queries but it doesn’t work when I use the code below.

def retrieve_data_single(table_name, date):
    
    
    conn = psycopg2.connect(host="localhost", port = 5432, database="db", user="user")
    cur = conn.cursor()

    date = date + "%"
    
    cur.execute("""SELECT open, date FROM table_name WHERE date LIKE (%s)""" , [date])

retrieve_data_single(table_1, '2022-12-12'):
    

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

According to:

Passing table name as a parameter in psycopg2

You should be using this

template:

from psycopg2 import sql
cur.execute(
    sql.SQL("insert into {table} values (%s, %s)")
        .format(table=sql.Identifier('my_table')), # table name here
    [10, 20]) ## other parameters here
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading