-
Notifications
You must be signed in to change notification settings - Fork 1
/
MysqlConn.py
67 lines (60 loc) · 1.87 KB
/
MysqlConn.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
import pymysql
class MysqlConn:
def __init__(self, host, port, user, password, database):
self.conn = None
self.cursor = None
self.__host = host
self.__port = port
self.__user = user
self.__password = password
self.__database = database
def connect(self):
try:
self.conn = pymysql.connect(host=self.__host, port=self.__port, user=self.__user, password=self.__password,
database=self.__database, charset="utf8")
self.cursor = self.conn.cursor()
except Exception as e:
print(e)
return False
else:
return True
def close(self):
self.cursor.close()
self.conn.close()
def execute(self, sql, params=None):
try:
self.connect()
self.cursor.execute(sql, params)
self.conn.commit()
except Exception as e:
print("SQL Execute error: " + str(e))
print("Original SQL: " + sql)
self.conn.rollback()
return False
else:
return True
def fetch_one(self, sql):
try:
self.connect()
self.cursor.execute(sql)
result = self.cursor.fetchone()
self.close()
except Exception as e:
print("SQL fetch error: " + str(e))
print("Original SQL: " + sql)
result = None
if result is None:
return None
else:
return result
def fetch_all(self, sql):
try:
self.connect()
self.cursor.execute(sql)
result = self.cursor.fetchall()
self.close()
except Exception as e:
print("SQL fetchall error: " + str(e))
print("Original SQL: " + sql)
result = ()
return result