添加 MySQL Dao
This commit is contained in:
7
config/mysql_config.json
Normal file
7
config/mysql_config.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"host": "rm-1udh78538ph225j525o.mysql.rds.aliyuncs.com",
|
||||||
|
"port": 3306,
|
||||||
|
"user": "nbaertuo",
|
||||||
|
"password": "aliClon1",
|
||||||
|
"db_name": "bet"
|
||||||
|
}
|
||||||
52
dao/Database.py
Normal file
52
dao/Database.py
Normal file
@@ -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()
|
||||||
0
dao/__init__.py
Normal file
0
dao/__init__.py
Normal file
Reference in New Issue
Block a user