-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathmysql.py
89 lines (73 loc) · 2.29 KB
/
mysql.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb
import time
class MySQL:
error_code = ''
_instance = None
_conn = None
_cursor = None
_TIMEOUT = 30
_timecount = 0
def __init__(self, cfg):
try:
self._conn = MySQLdb.connect(
host = cfg["host"],
port = cfg["port"],
user = cfg["user"],
passwd = cfg["passwd"],
db = cfg["db"],
charset = cfg["charset"]
)
except MySQLdb.Error as e:
self.error_code = e.args[0]
print "MySQL error %d: %s" % (e.args[0], e.args[1])
# Try to reconnect if not timeout
if self._timeout < self._TIMEOUT:
interval = 5
self._timecout += interval
time.sleep(interval)
return self.__init__(cfg)
else:
raise Exception(error_msg)
self._cursor = self._conn.cursor()
self._instance = MySQLdb
def query(self, sql):
try:
self._cursor.execute("SET NAMES utf8")
result = self._cursor.execute(sql)
except MySQLdb.Error, e:
self.error_code = e.args[0]
print "MySQL error %d: %s" % (e.args[0], e.args[1])
result = False
return result
def update(self, sql):
try:
self._cursor.execute("SET NAMES utf8")
result = self._cursor.execute(sql)
self._conn.commit()
except MySQLdb.Error as e:
self.error_code = e.args[0]
print "MySQL error %d: %s" % (e.args[0], e.args[1])
result = False
return result
def insert(self, sql):
try:
self._cursor.execute("SET NAMES utf8")
self._cursor.execute(sql)
self._conn.commit()
return self._conn.insert_id()
except MySQLdb.Error as e:
self.error_code = e.args[0]
print "MySQL error %d: %s" % (e.args[0], e.args[1])
return False
def getRowCount(self):
return self._cursor.rowcount
def __del__(self):
try:
self._cursor.close()
self._conn.close()
except:
pass
def close(self):
self.__del__()