-
Notifications
You must be signed in to change notification settings - Fork 1
/
db_utils.py
66 lines (52 loc) · 1.44 KB
/
db_utils.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import sqlite3
import io
import numpy as np
dbname = 'db/fencoding'
table_name = 'fencoding'
def adapt_array(arr):
"""
http://stackoverflow.com/a/31312102/190597 (SoulNibbler)
"""
out = io.BytesIO()
np.save(out, arr)
out.seek(0)
return sqlite3.Binary(out.read())
def convert_array(text):
out = io.BytesIO(text)
out.seek(0)
return np.load(out)
def init():
global conn
global c
# Converts np.array to TEXT when inserting
sqlite3.register_adapter(np.ndarray, adapt_array)
# Converts TEXT to np.array when selecting
sqlite3.register_converter("array", convert_array)
conn = sqlite3.connect(dbname, detect_types=sqlite3.PARSE_DECLTYPES)
c = conn.cursor()
def create_table():
sql = '''create table if not exists {}(
ID integer primary key AUTOINCREMENT,
NAME TEXT,
FENCODING array,
ACCESS_LVL integer)'''.format(table_name)
c.execute(sql)
def clear_table():
sql = 'drop table ' + table_name
c.execute(sql)
def remake_table():
clear_table()
create_table()
def insert_record(name, fencoding, alvl):
sql = '''insert into {} (NAME, FENCODING, ACCESS_LVL)
values (?, ?, ?)'''.format(table_name)
c.execute(sql, (name, fencoding, alvl))
def get_encodings():
sql = '''select NAME, FENCODING from {}'''.format(table_name)
c.execute(sql)
data = c.fetchall()
return data
def fcommit():
conn.commit()
c.close()
conn.close()