简体   繁体   中英

How insert variables into SQL query in Python?

I want to get data from the SQL database, however, sometimes the filter condition in SQL query should be changed (dates).

Python code is working when filters of the dates are inside query:

import vertica_python

conn_info = {'host': 'unreachable.server.com',
             'port': 888,
             'user': 'some_user',
             'password': 'some_password',
             'database': 'a_database',
             'backup_server_node': ['123.456.789.123', 'invalid.com', ('10.20.82.77', 6000)]}
connection = vertica_python.connect(**conn_info)

cur = connection.cursor()
start_date = '2020-06-25'
end_date = '2020-07-25'
cur.execute("""
SELECT price as price, volume as volume
FROM My_DB

WHERE START_TS >= '2020-06-25'
and START_TS <= '2020-07-25'
ORDER BY price
                """) 
df = pd.DataFrame(cur.fetchall())

However, I want to replace dates with variables start_date and end_date I tried following approaches with format and f-type strings , however there was an error (Query error).

cur.execute(f"""
SELECT price as price, volume as volume
FROM My_DB

WHERE START_TS >= {start_date }
and START_TS <= {end_date }
ORDER BY price
                """) 
df = pd.DataFrame(cur.fetchall())

and

cur.execute("""
SELECT price as price, volume as volume
FROM My_DB

WHERE START_TS >= {}
and START_TS <= {}
ORDER BY price
                """.format(start_date ,end_date )) 
df = pd.DataFrame(cur.fetchall())

Use quotes to enclose your variables: '{start_date }' and '{end_date }'

cur.execute(f"""
SELECT price as price, volume as volume
FROM My_DB

WHERE START_TS >= '{start_date }'
and START_TS <= '{end_date }'
ORDER BY price
                """) 
df = pd.DataFrame(cur.fetchall())

Avoid SQL injection

connection = vertica_python.connect(**conn_info)

start_date = '2020-06-25'
end_date = '2020-07-25'

# not sure about the %s placeholder; you may need to use ? instead
# the engine takes care of the quoting (if required) for you
sql = """
    SELECT price as price, volume as volume
    FROM My_DB

    WHERE START_TS >= %s
        AND START_TS <= %s
    ORDER BY price
    """

df = pd.readsql(sql, connection, params=(start_date, end_date))

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