import pymysql
from typing import List, Dict, Optional
from datetime import datetime
class MySQLDB:
def __init__(self):
self.conn = None
self.cursor = None
def connect(self):
"""连接数据库"""
try:
self.conn = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='123456',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor # 返回字典格式
)
self.cursor = self.conn.cursor()
except Exception as e:
print(f"连接数据库失败:{e}")
raise e
def close(self):
"""关闭数据库连接"""
if self.cursor:
self.cursor.close()
if self.conn:
self.conn.close()
2.2 数据库和表操作
def create_database(self):
"""创建数据库"""
try:
sql = "CREATE DATABASE IF NOT EXISTS test DEFAULT CHARACTER SET utf8mb4"
self.cursor.execute(sql)
self.conn.select_db('test') # 选择数据库
except Exception as e:
print(f"创建数据库失败:{e}")
raise e
def drop_database(self):
"""删除数据库"""
try:
sql = "DROP DATABASE IF EXISTS test"
self.cursor.execute(sql)
except Exception as e:
print(f"删除数据库失败:{e}")
raise e
def c