-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvndb.py
executable file
·269 lines (236 loc) · 8.27 KB
/
vndb.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import MySQLdb
import MySQLdb.cursors
" MySQL OP Helper "
__author__ = 'Vien'
class DBHelper(object):
def __init__(self, host, user, passwd, schema, charset='utf8mb4',
autocommit=True):
# reload(sys)
# sys.setdefaultencoding('utf-8')
self._db_conf = {
'user': user,
'passwd': passwd,
'host': host,
'db': schema,
'charset': charset
}
self._autocommit = autocommit
self._conn = None
self._dict_cursor = None
self._tuple_cursor = None
self._current_cursor = None
def __enter__(self):
self.get_conn()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def escape_str(self, s):
return MySQLdb.escape_string(s)
def literal(self, s):
return self._conn.literal(s)
def format_param(self, param, batch=False):
if param:
if batch:
return [i if (isinstance(i, tuple) or isinstance(i, list)) else [i] for i in param]
return ((isinstance(param, tuple) or isinstance(param, list)) and [param] or [[param]])[0]
return None
def get_last_sql(self):
if self._current_cursor:
return self._current_cursor._executed
return False
def get_rowcount(self):
if self._current_cursor:
return int(self._current_cursor.rowcount)
return False
def auto_commit(self, flag=True):
self._autocommit = flag
def begin(self):
self._autocommit = False
def end(self):
self._conn.commit()
self._autocommit = True
def use_schema(self, schema):
try:
self._conn.select_db(schema)
except Exception as e:
raise e
def get_conn(self):
if self._conn:
self._conn.ping()
return self._conn
try:
self._conn = MySQLdb.connect(**self._db_conf)
except Exception as e:
raise e
return self._conn
def get_cursor(self, cursorclz=None):
if not self._conn:
self.get_conn()
else:
self._conn.ping()
try:
cursor = self._conn.cursor(cursorclass=cursorclz)
except Exception as e:
raise e
return cursor
def close(self):
if self._conn:
try:
if self._dict_cursor:
self._dict_cursor.close()
if self._tuple_cursor:
self._tuple_cursor.close()
if self._conn:
self._conn.close()
except Exception as e:
raise e
def get_last_id(self, table, pri='id'):
last_id = self.get_values(" SELECT `%s` FROM `%s` ORDER BY `%s` DESC LIMIT 1 " % (pri, table, pri))
return last_id[0] if last_id else False
def show_variable(self, var_name):
res = self.get_values(" SHOW VARIABLES LIKE '%{}%' ".format(var_name))
return res[0] if res else False
def get_dicts(self, sql, params=None, convert=True):
if not self._dict_cursor:
self._dict_cursor = self.get_cursor(MySQLdb.cursors.DictCursor)
else:
self._conn.ping()
try:
self._dict_cursor.execute(sql, self.format_param(params))
self._current_cursor = self._dict_cursor
res = self._dict_cursor.fetchall()
if res:
if convert:
return list(res)
else:
return res
except Exception as e:
raise e
return False
def get_values(self, sql, params=None, convert=True):
if not self._tuple_cursor:
self._tuple_cursor = self.get_cursor()
else:
self._conn.ping()
try:
self._tuple_cursor.execute(sql, self.format_param(params))
self._current_cursor = self._tuple_cursor
res = self._tuple_cursor.fetchall()
if res:
if convert:
res_list = [(len(item) == 1 and [item[0]] or [item])[0] for item in res]
return res_list
else:
return res
except Exception as e:
raise e
return False
def execute(self, sql, params=None):
if not self._tuple_cursor:
self._tuple_cursor = self.get_cursor()
else:
self._conn.ping()
try:
self._tuple_cursor.execute(sql, self.format_param(params))
self._current_cursor = self._tuple_cursor
if self._autocommit:
self._conn.commit()
except Exception as e:
self._conn.rollback()
raise e
return self.get_rowcount()
def execute_batch(self, sql, params, step_size=2000):
if not params:
raise Exception("No params")
if not self._current_cursor:
self._tuple_cursor = self.get_cursor()
self._current_cursor = self._tuple_cursor
else:
self._conn.ping()
row_count = 0
try:
size = int(step_size)
length = len(params)
size = size if length >= size else length
params = self.format_param(params, True)
for i in xrange(0, (length + size - 1) / size):
self._current_cursor.executemany(sql, params[i * size:(i + 1) * size])
row_count = row_count + self.get_rowcount()
if self._autocommit:
self._conn.commit()
except Exception as e:
self._conn.rollback()
raise e
return row_count
def insert_batch(self, sql, params, step_size=2000):
if not params:
raise Exception("No params")
if not self._current_cursor:
self._tuple_cursor = self.get_cursor()
self._current_cursor = self._tuple_cursor
else:
self._conn.ping()
try:
size = int(step_size)
length = len(params)
size = size if length >= size else length
params = self.format_param(params, True)
pos = sql.rfind('(')
values = []
for i in xrange(0, (length + size - 1) / size):
sql_left = sql[:pos]
sql_right = sql[pos:]
for args in params[i * size:(i + 1) * size]:
for arg in args:
values.append(arg)
sql_left = sql_left + sql_right + ','
sql_final = sql_left[:sql_left.rfind(',')]
# print(sql_final)
self._current_cursor.execute(sql_final, values)
if self._autocommit:
self._conn.commit()
except Exception as e:
self._conn.rollback()
raise e
return self.get_rowcount()
def get_fields_and_types(self, table, no_pri=False):
sql = ' DESC %s ' % table
res = self.get_dicts(sql)
props = dict()
for item in res:
if no_pri and item['Key'] == 'PRI':
continue
type = item['Type']
pos = type.find('(')
type = type[:pos if pos != -1 else len(type)] # pos != -1 and pos or len(type)
props[item['Field']] = type
return props
def get_fields_types_lens(self, table, no_pri=False):
sql = ' DESC %s ' % table
res = self.get_dicts(sql)
props = dict()
for item in res:
if no_pri and item['Key'] == 'PRI':
continue
props[item['Field']] = item['Type']
return props
def get_fields(self, table, no_pri=False):
props = self.get_fields_types_lens(table, no_pri)
return [k for k, v in props.items()]
def show_create_table(self, table):
sql = ' SHOW CREATE TABLE %s ' % table
res = self.get_dicts(sql)
return res[0]['Create Table'] if res else False
if __name__ == '__main__':
db_conf = {
'user': 'vien',
'passwd': 'vien',
'host': '127.0.0.1',
'schema': 'vien',
'charset': 'utf8mb4'
}
with DBHelper(**db_conf) as db:
print(db.show_variable("max_allowed_packet"))