-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrapper_style_connector.py
More file actions
59 lines (47 loc) · 1.77 KB
/
wrapper_style_connector.py
File metadata and controls
59 lines (47 loc) · 1.77 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
55
56
57
58
59
# -*- coding: utf-8 -*-
import json
import pymysql
import progressbar
import functools
def mysql_decorator(func):
"""
Decorates function with code that connects to mysql database. Connection class is passed as first argument to func.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
with open('database_keys.json') as f:
data = json.load(f)
db = pymysql.connect(host=data["host"],
user=data["user"],
passwd=data["passwd"],
db=data["db"])
# func.__globals__['db'] = db
# eariler version injected db directly to func
# I abonded it due to bad readability and messing with globals can easily backfire (threads etc)
func(db, *args, **kwargs)
db.commit()
db.close()
return wrapper
@mysql_decorator
def insert_list(db, table_name, data):
"""
Inserts data to mysql database. Its not sonic but can do the trick for small datasets.
It takes 15 sec to make about 300 inserts. For bigger datasets better go with file import.
:param str table_name: Name of mysql table
:param list data: Contains list of values. Values should also by a list
"""
for foo in progressbar.progressbar(data):
str_values = "\'"
str_values += "\', \'".join(foo)
str_values += "\'"
with db.cursor() as cursor:
sql = "INSERT INTO %s VALUES (%s);" % (table_name, str_values)
cursor.execute(sql)
@mysql_decorator
def delete_data_of_table(db, table_name):
"""
Delete all data from table
:param str table_name: Name of the table to drop.
"""
db.cursor().execute("DELETE FROM %s;" % table_name)
print("Table %s has been cleared\n" % table_name)