From 3d691eb22c4e8559693a0fc4fd9d74ce3160cd32 Mon Sep 17 00:00:00 2001 From: aszerW Date: Sun, 11 Aug 2024 18:28:23 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20MySQL=20Dao?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/mysql_config.json | 7 ++++++ dao/Database.py | 52 ++++++++++++++++++++++++++++++++++++++++ dao/__init__.py | 0 3 files changed, 59 insertions(+) create mode 100644 config/mysql_config.json create mode 100644 dao/Database.py create mode 100644 dao/__init__.py diff --git a/config/mysql_config.json b/config/mysql_config.json new file mode 100644 index 0000000..1743c84 --- /dev/null +++ b/config/mysql_config.json @@ -0,0 +1,7 @@ +{ + "host": "rm-1udh78538ph225j525o.mysql.rds.aliyuncs.com", + "port": 3306, + "user": "nbaertuo", + "password": "aliClon1", + "db_name": "bet" +} \ No newline at end of file diff --git a/dao/Database.py b/dao/Database.py new file mode 100644 index 0000000..db3a413 --- /dev/null +++ b/dao/Database.py @@ -0,0 +1,52 @@ +import pymysql.cursors +from data_model import MysqlConfig + +class Database: + def __init__(self, config: MysqlConfig): + self.config = config + self.connection = None + + def connect(self): + if not self.connection or not self.connection.open: + self.connection = pymysql.connect( + host=self.config.host, + user=self.config.user, + password=self.config.password, + database=self.config.db_name, + port=self.config.port, + cursorclass=pymysql.cursors.DictCursor + ) + return self.connection + + def close(self): + if self.connection and self.connection.open: + self.connection.close() + + def execute(self, query, args=None): + connection = self.connect() + try: + with connection.cursor() as cursor: + cursor.execute(query, args) + connection.commit() + finally: + self.close() + + def fetchone(self, query, args=None): + connection = self.connect() + try: + with connection.cursor() as cursor: + cursor.execute(query, args) + result = cursor.fetchone() + return result + finally: + self.close() + + def fetchall(self, query, args=None): + connection = self.connect() + try: + with connection.cursor() as cursor: + cursor.execute(query, args) + results = cursor.fetchall() + return results + finally: + self.close() diff --git a/dao/__init__.py b/dao/__init__.py new file mode 100644 index 0000000..e69de29