python-module-pgsql/manage_psql/manage_psql.py

86 lines
2.5 KiB
Python
Raw Normal View History

2019-12-03 11:11:52 +01:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Module psql connection."""
# /*
# * ----------------------------------------------------------------------------
# * "THE BEER-WARE LICENSE" (Revision 42):
# * <boris.tassou@securmail.fr> wrote this file. As long as you retain this notice you
# * can do whatever you want with this stuff. If we meet some day, and you think
# * this stuff is worth it, you can buy me a beer in return Boris Tassou
# * ----------------------------------------------------------------------------
# */
from configparser import SafeConfigParser
import psycopg2
class HandlePsql:
"""Class to handle psql connection."""
conn = None
cur = None
@staticmethod
def psql_conn():
"""Init psql connection."""
# Read conf.ini
ini_conf = "/usr/local/Securmail-Administration/config/conf.ini"
config = SafeConfigParser()
config.read(ini_conf)
# DB parameters
psql_host = config.get('psql', 'host')
psql_db = config.get('psql', 'database')
psql_user = config.get('psql', 'user')
psql_pwd = config.get('psql', 'passwd')
# connexion DB
# http://initd.org/psycopg/docs/usage.html
# http://www.postgresqltutorial.com/postgresql-python/
try:
global conn
conn = psycopg2.connect(host=psql_host, database=psql_db, user=psql_user, password=psql_pwd)
conn.cursor()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
@staticmethod
def psql_select(sql_select):
"""Psql select request."""
cur = conn.cursor()
cur.execute(sql_select)
sql_return = cur.fetchall()
return sql_return
@staticmethod
def psql_delete(sql_delete):
"""Psql delte request."""
cur = conn.cursor()
cur.execute(sql_delete)
conn.commit()
@staticmethod
def psql_insert(sql_insert):
"""Psql insert request."""
cur = conn.cursor()
cur.execute(sql_insert)
conn.commit()
@staticmethod
def psql_update(sql_update):
"""Psql insert request."""
cur = conn.cursor()
cur.execute(sql_update)
conn.commit()
@staticmethod
def psql_unconn():
"""End psql connection."""
cur = conn.cursor()
cur.close()
conn.close()
if __name__ == "__main__":
print("Module psql to handle the connection")