Skip to content

Instantly share code, notes, and snippets.

@garystafford
Last active November 23, 2018 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garystafford/a6acc66bdafbf42583b663479577799b to your computer and use it in GitHub Desktop.
Save garystafford/a6acc66bdafbf42583b663479577799b to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import psycopg2
# source: https://stackoverflow.com/questions/45805871/python3-psycopg2-execute-sql-file
connect_str = 'host=postgres port=5432 dbname=demo user=postgres password=postgres1234'
conn = psycopg2.connect(connect_str)
conn.autocommit = True
cursor = conn.cursor()
sql_file = open('bakery_sample.sql', 'r')
sqlFile = sql_file.read()
sql_file.close()
sqlCommands = sqlFile.split(';')
for command in sqlCommands:
print(command)
if command.strip() != '':
cursor.execute(command)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment