scripts/lib/mysql.py

49 lines
1.2 KiB
Python

import pymysql
from lib.log import *
class Mysql:
def __init__(self, host, port=3306, db='test', user=None, pwd=None):
""" 初始化Mysql数据库和表的信息并连接数据库
:param host: 数据库实例ip
:param port: 数据库实例端口
:param db: 数据库名
:param user: 用户名
:param password: 密码
"""
self.host = host
self.port = port
self.db = db
self.user = user
self.pwd = pwd
self.conn = pymysql.connect(
host=host,
port=port,
user=user,
password=pwd,
db=db,
cursorclass=pymysql.cursors.DictCursor
)
if not self.conn:
print("连接失败")
def close(self):
self.conn.close()
def exec(self, sql, data):
with self.conn.cursor() as cursor:
cursor.execute(sql, data)
return self.conn.commit()
def query(self, sql):
with self.conn.cursor() as cursor:
cursor.execute(sql)
return cursor.fetchall()
def get_mysql_db_vas():
return Mysql(
"rm-bp11t1616a1kjvmx5.mysql.rds.aliyuncs.com", 3306, "vas", "root", "Wishpal2024"
)