LoginSignup
0
1

More than 1 year has passed since last update.

Python から PostgreSQLに接続 備忘録

Posted at

psycopg2インストール

pg_config --version ・・・入っているかの確認
sudo apt-get install libpq-dev ・・・なければインストール
pip3 install psycopg2

メモ:「pg_config 」がないとエラーになりインストール不可。

記述例

dbの接続情報は別にjsonファイルを用意する

#!/usr/bin/env python3
import psycopg2,json,os,platform,subprocess,sys

dirname =os.path.dirname(__file__)
print('dirname:',dirname)
file = open(dirname + str('/info_db.json'),'r')
info_db = json.load(file)

userName=info_db['user_Linux']
osName=str(platform.system())
if osName == 'Windows':
      userName =info_db['user_Windows']

con = psycopg2.connect(
    host = info_db['host'],
    port = info_db['port'],
    database=info_db['database'],
    user=userName,
    password=info_db['password'])

cur1 = con.cursor()
cur1.execute('select cast(count(*) as INTEGER) from f_overdue_task()')
cur2 = con.cursor()
cur2.execute('select * from f_overdue_task()')


try:
    count = cur1.fetchone()
    print('レコード件数:'+str(count[0]))
    if count[0] ==0:
        sys.exit()
    mesStr='【超過タスクのお知らせ】\n'
    cnt=0
    for row in cur2:
        rec=(str(row[0])+','+str(row[1])+'の'+str(row[2])+'/'+str(row[3])+'日')
        mesStr = mesStr + rec + '\n'
        cnt = cnt+1
    print(mesStr)

    osName=str(platform.system())
    cmd='python3'
    if osName == 'Windows':
        cmd ='python'
    print( "OS:" + osName + '_cmd:' + cmd)
    dirname =os.path.dirname(__file__)
    dirPy = dirname + str('/sampleLine.py')
    subprocess.run([cmd,dirPy,mesStr])
except SystemExit:
    print('【超過タスクなし】')
except:
    print('予期せぬエラー')
finally:
    cur1.close()
    cur2.close()
    con.close()

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1