Created
August 24, 2021 21:11
-
-
Save stephane-klein/b84ceae2ae2c94511a48002b9b70cf26 to your computer and use it in GitHub Desktop.
sql_builder_insert Python example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from psycopg2 import sql | |
import queries | |
pg_session = queries.Session( | |
queries.uri( | |
host='localhost', | |
port='5439', | |
dbname='postgres', | |
user='postgres', | |
password='password' | |
) | |
) | |
def sql_builder_insert(base_query, data_dict): | |
return sql.SQL(base_query).format( | |
sql.SQL(', ').join(map(sql.Identifier, data_dict.keys())), | |
sql.SQL(', ').join(map(sql.Literal, data_dict.values())) | |
).as_string(pg_session.connection) | |
response = pg_session.query( | |
sql_builder_insert( | |
"INSERT INTO foobar ({}) values ({}) ON CONFLICT DO NOTHING RETURNING id", | |
{ | |
"login": login, | |
"name": name | |
} | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment