aboutsummaryrefslogtreecommitdiffstats
path: root/python/db.py
blob: 1fe42b85e0cde522b0e1ad78460ee76ec1a3a2b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import psycopg2
from psycopg2.extras import DictCursor

conn = psycopg2.connect(database="ET",
                        user="et_user",
                        password="Serenitas1",
                        host="debian",
                        cursor_factory=DictCursor)

def with_connection(f):
    def with_connection_(*args, **kwargs):
        # or use a pool, or a factory function...
        try:
            rv = f(conn, *args, **kwargs)
        except Exception as e:
            print(e)
            conn.rollback()
        else:
            return rv

    return with_connection_

@with_connection
def query_db(conn, sqlstr, params=None, one=True):
    c = conn.cursor()
    if params:
        c.execute(sqlstr, params)
    else:
        c.execute(sqlstr)
    if one:
        return c.fetchone()
    else:
        return c.fetchall()
    c.close()