Skip to content

Instantly share code, notes, and snippets.

@stephane-klein
Created August 24, 2021 21:11
Show Gist options
  • Save stephane-klein/b84ceae2ae2c94511a48002b9b70cf26 to your computer and use it in GitHub Desktop.
Save stephane-klein/b84ceae2ae2c94511a48002b9b70cf26 to your computer and use it in GitHub Desktop.
sql_builder_insert Python example
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