This repository was archived by the owner on Jul 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMySQL.py
More file actions
55 lines (40 loc) · 1.57 KB
/
MySQL.py
File metadata and controls
55 lines (40 loc) · 1.57 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
from json import load as json_load
import pymysql.cursors
from pymysql.constants import CLIENT
class MySQL:
def __init__(self, config_path):
with open(config_path, 'r', encoding="utf-8") as config_file:
config = json_load(config_file, encoding="utf-8")
self.host = config["db_hostname"]
self.user = config["db_username"]
self.password = config["db_password"]
self.db = config["db_name"]
# self.charset = config["charset"]
self.connection = pymysql.connect(host=self.host,
user=self.user,
password=self.password,
db=self.db,
cursorclass=pymysql.cursors.DictCursor,
autocommit=False,
client_flag=CLIENT.MULTI_STATEMENTS)
def __del__(self):
self.commit()
self.close()
def query(self, sql, args=None):
with self.connection.cursor() as cursor:
rows_num = cursor.execute(sql, args)
return rows_num
def fetch(self, sql, args=None):
with self.connection.cursor() as cursor:
cursor.execute(sql, args)
data = cursor.fetchall()
return data
def commit(self):
self.connection.commit()
def close(self):
self.connection.close()
def main():
mysql = MySQL("../config.json")
print(mysql.query("SELECT * FROM `users`"))
if __name__ == "__main__":
main()