Skip to content

Instantly share code, notes, and snippets.

@TearTheSky
Last active January 13, 2021 14:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TearTheSky/9d2e0745e409d3cd617d to your computer and use it in GitHub Desktop.
Save TearTheSky/9d2e0745e409d3cd617d to your computer and use it in GitHub Desktop.
PostgreSQLのDBに対して引数で与えたSQLファイルの内容を実行するPythonサンプル
#!/usr/bin/python
# coding: utf-8
import sys
import psycopg2
def execute_sql_from_file(sqlfile):
try:
cnn = psycopg2.connect("dbname=my_db host=my_db_endpoint user=postgres password=my_password")
cur = cnn.cursor()
target_sql_file = open(sqlfile)
sql_data = target_sql_file.read() # ファイル終端まで全て読んだデータを返す
target_sql_file.close()
cnn.commit()
cur.execute(sql_data)
rows = cur.fetchall()
cur.close()
cnn.close()
return rows
except (psycopg2.OperationalError) as e:
print (e)
## 関数実行(Main処理相当)
if __name__ == "__main__":
my_result = execute_sql_from_file( sys.argv[1] )
print(my_result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment