python
复制代码
import pymysql
from config.config import MYSQL_HOST, MYSQL_USER, MYSQL_PASSWD, MYSQL_PROT, MYSQL_DB, MYSQL_CHARSET
class MysqlDB():
def __init__(self, MYSQL_HOST, MYSQL_USER, MYSQL_PASSWD, MYSQL_PROT, MYSQL_DB, MYSQL_CHARSET):
self.mysql = pymysql.connect(
host=MYSQL_HOST, # 连接名称,默认127.0.0.1
user=MYSQL_USER, # 用户名
passwd=MYSQL_PASSWD, # 密码
port=MYSQL_PROT, # 端口,默认为3306
db=MYSQL_DB, # 数据库名称
charset=MYSQL_CHARSET, # 字符编码
)
def get(self):
self.mysql.ping(reconnect=True)
cursor = self.mysql.cursor()
# 执行一个简单的SELECT语句
cursor.execute("select * from test")
# 获取结果
results = cursor.fetchall()
cursor.close()
return results
def get_index_by_id(self,id):
self.mysql.ping(reconnect=True)
cursor = self.mysql.cursor()
# 执行一个简单的SELECT语句
cursor.execute(f"select * from test where id = {id}")
# 获取结果
results = cursor.fetchall()
cursor.close()
return results
mysql_db = MysqlDB(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWD, MYSQL_PROT, MYSQL_DB, MYSQL_CHARSET)