-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql.py
More file actions
54 lines (47 loc) · 1.52 KB
/
sql.py
File metadata and controls
54 lines (47 loc) · 1.52 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/bin/env python
import psycopg2
# default values
class SQL:
user = "user"
pwd = "123456"
host = "localhost"
db = "data"
hist_table = "historicaldata"
create_hist_table = """
create table if not exists historicaldata (
symbol varchar(10),
date date,
volume integer,
low numeric,
high numeric,
close numeric,
open numeric,
adj_close numeric
);
"""
class sql_sink:
def __init__(self, dbname, host, user, pwd, table=SQL.hist_table):
self.conn_str_ = "dbname=%s user=%s password=%s" % (dbname, user, pwd)
self.table_ = table
def log_hist(self, data, filter=None):
entries = []
for symbol in data:
for d in data[symbol].items():
if filter is None or filter(d):
entries.append(d.values())
try:
conn = psycopg2.connect(self.conn_str_)
cur = conn.cursor()
# create table if doesn't exist
cur.execute(SQL.create_hist_table)
# insert data
sql = "insert into %s values" % self.table_
cur.executemany(sql + " (%s,%s,%s,%s,%s,%s,%s,%s)", entries)
conn.commit()
cur.close()
conn.close()
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
import traceback
traceback.print_exception(exc_type, exc_value, exc_traceback)
print("Failed to execute SQL query.")