Last active
January 13, 2021 14:58
-
-
Save TearTheSky/9d2e0745e409d3cd617d to your computer and use it in GitHub Desktop.
PostgreSQLのDBに対して引数で与えたSQLファイルの内容を実行するPythonサンプル
This file contains hidden or 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
#!/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