-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDatabase.py
38 lines (32 loc) · 1.06 KB
/
Database.py
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
35
36
37
38
import json
import datetime
import psycopg2
class Database:
timeFormat = '%Y-%m-%d %H:%M:%S'
cur = None
conn = None
def __init__(self, cfg):
username = cfg['username']
password = cfg['password']
host = cfg['host']
databasename = cfg['databasename']
self.conn = psycopg2.connect(host = host, user = username, password = password, dbname = databasename)
self.cur = self.conn.cursor()
def insert(self, data, name):
if len(data) <= 0:
return
now = datetime.datetime.now()
keys = 'time'
values = [now.strftime(self.timeFormat)]
replacement = '%s'
for key, value in data.items():
keys += ', ' + key
values += [value]
replacement += ', %s'
query = "INSERT INTO %s (%s) VALUES (%s)" % (name, keys, replacement)
print(query, values)
self.cur.execute(query, values)
self.conn.commit()
def __exit__(self, exc_type, exc_value, traceback):
self.cur.close()
self.conn.close()