专栏导读
🌸 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手
🏳️🌈 博客主页:请点击——> 一晌小贪欢的博客主页求关注
👍 该系列文章专栏:请点击——>Python办公自动化专栏求订阅
🕷 此外还有爬虫专栏:请点击——>Python爬虫基础专栏求订阅
📕 此外还有python基础专栏:请点击——>Python基础学习专栏求订阅
文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏
❤️ 欢迎各位佬关注! ❤️
题目: 数据库 - 创建简单的数据库管理系统
答案代码
class DatabaseManager:
def __init__(self, db_name='test.db'):
self.db_name = db_name
self.connection = None
self.tables = {}
self.init_database()
def init_database(self):
"""初始化数据库(模拟)"""
try:
# 在实际应用中,这里会使用sqlite3或其他数据库
# 这里我们用字典模拟数据库表
print(f"初始化数据库: {self.db_name}")
# 创建用户表
self.create_table('users', {
'id': 'INTEGER PRIMARY KEY',
'username': 'TEXT UNIQUE NOT NULL',
'email': 'TEXT UNIQUE NOT NULL',
'age': 'INTEGER',
'created_at': 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP'
})
# 创建产品表
self.create_table('products', {
'id': 'INTEGER PRIMARY KEY',
'name': 'TEXT NOT NULL',
'price': 'REAL NOT NULL',
'category': 'TEXT',
'stock': 'INTEGER DEFAULT 0',
'created_at': 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP'
})
# 创建订单表
self.create_table('orders', {
'id': 'INTEGER PRIMARY KEY',
'user_id': 'INTEGER',
'product_id': 'INTEGER',
'quantity': 'INTEGER NOT NULL',
'total_price': 'REAL NOT NULL',
'order_date': 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP'
})
print("数据库初始化完成")
return True
except Exception as e:
print(f"数据库初始化失败: {e}")
return False
def create_table(self, table_name, columns):
"""创建表"""
try:
# 模拟表结构
self.tables[table_name] = {
'columns': columns,
'data': [],
'next_id': 1
}
column_defs = []
for col_name, col_type in columns.items():
column_defs.append(f"{col_name} {col_type}")
sql = f"CREATE TABLE {table_name} ({', '.join(column_defs)})"
print(f"创建表: {table_name}")
print(f"SQL: {sql}")
return True
except Exception as e:
print(f"创建表失败: {e}")
return False
def insert_record(self, table_name, data):
"""插入记录"""
try:
if table_name not in self.tables:
raise ValueError(f"表 {table_name} 不存在")
table = self.tables[table_name]
# 自动分配ID
if 'id' in table['columns'] and 'id' not in data:
data['id'] = table['next_id']
table['next_id'] += 1
# 添加时间戳
if 'created_at' in table['columns'] and 'created_at' not in data:
from datetime import datetime
data['created_at'] = datetime.now().isoformat()
# 验证必需字段
for col_name, col_type in table['columns'].items():
if 'NOT NULL' in col_type and col_name not in data:
if 'DEFAULT' not in col_type and col_name != 'id':
raise ValueError(f"字段 {col_name} 不能为空")
# 检查唯一性约束
for col_name, col_type in table['columns'].items():
if 'UNIQUE' in col_type and col_name in data:
for existing_record in table['data']:
if existing_record.get(col_name) == data[col_name]:
raise ValueError(f"字段 {col_name} 的值 '{data[col_name]}' 已存在")
# 插入数据
table['data'].append(data.copy())
print(f"成功插入记录到表 {table_name}: {data}")
return data.get('id', len(table['data']))
except Exception as e:
print(f"插入记录失败: {e}")
return None
def select_records(self, table_name, conditions=None, limit=None, order_by=None):
"""查询记录"""
try:
if table_name not in self.tables:
raise ValueError(f"表 {table_name} 不存在")
table = self.tables[table_name]
results = table['data'].copy()
# 应用条件过滤
if conditions:
filtered_results = []
for record in results:
match = True
for field, value in conditions.items():
if isinstance(value, dict):
# 支持操作符 {'age': {'>=': 18}}
for op, op_value in value.items():
record_value = record.get(field)
if record_value is None:
match = False
break
if op == '=' or op == '==':
if record_value != op_value:
match = False
elif op == '!=':
if record_value == op_value:
match = False
elif op == '>':
if record_value <= op_value:
match = False
elif op == '>=':
if record_value < op_value:
match = False
elif op == '<':
if record_value >= op_value:
match = False
elif op == '<=':
if record_value > op_value:
match = False
else:
# 简单相等比较
if record.get(field) != value:
match = False
if not match:
break
if match:
filtered_results.append(record)
results = filtered_results
# 排序
if order_by:
if isinstance(order_by, str):
results.sort(key=lambda x: x.get(order_by, 0))
elif isinstance(order_by, dict):
for field, direction in order_by.items():
reverse = direction.upper() == 'DESC'
results.sort(key=lambda x: x.get(field, 0), reverse=reverse)
# 限制结果数量
if limit:
results = results[:limit]
print(f"查询表 {table_name} 返回 {len(results)} 条记录")
return results
except Exception as e:
print(f"查询记录失败: {e}")
return []
def update_records(self, table_name, conditions, updates):
"""更新记录"""
try:
if table_name not in self.tables:
raise ValueError(f"表 {table_name} 不存在")
table = self.tables[table_name]
updated_count = 0
for record in table['data']:
match = True
# 检查条件
if conditions:
for field, value in conditions.items():
if record.get(field) != value:
match = False
break
if match:
# 更新记录
for field, value in updates.items():
if field in table['columns']:
record[field] = value
updated_count += 1
print(f"更新表 {table_name} 中 {updated_count} 条记录")
return updated_count
except Exception as e:
print(f"更新记录失败: {e}")
return 0
def delete_records(self, table_name, conditions):
"""删除记录"""
try:
if table_name not in self.tables:
raise ValueError(f"表 {table_name} 不存在")
table = self.tables[table_name]
original_count = len(table['data'])
# 过滤出不匹配条件的记录
filtered_data = []
for record in table['data']:
match = True
if conditions:
for field, value in conditions.items():
if record.get(field) != value:
match = False
break
if not match:
filtered_data.append(record)
table['data'] = filtered_data
deleted_count = original_count - len(table['data'])
print(f"从表 {table_name} 删除 {deleted_count} 条记录")
return deleted_count
except Exception as e:
print(f"删除记录失败: {e}")
return 0
def get_table_info(self, table_name):
"""获取表信息"""
if table_name not in self.tables:
return None
table = self.tables[table_name]
return {
'name': table_name,
'columns': table['columns'],
'record_count': len(table['data']),
'next_id': table['next_id']
}
def list_tables(self):
"""列出所有表"""
return list(self.tables.keys())
def backup_database(self, backup_file='database_backup.json'):
"""备份数据库"""
try:
import json
from datetime import datetime
backup_data = {
'database_name': self.db_name,
'backup_time': datetime.now().isoformat(),
'tables': self.tables
}
with open(backup_file, 'w', encoding='utf-8') as f:
json.dump(backup_data, f, ensure_ascii=False, indent=2)
print(f"数据库已备份到: {backup_file}")
return True
except Exception as e:
print(f"备份失败: {e}")
return False
def generate_report(self):
"""生成数据库报告"""
from datetime import datetime
report = []
report.append("=" * 60)
report.append(f"数据库报告: {self.db_name}")
report.append("=" * 60)
report.append(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
report.append("")
report.append(f"表数量: {len(self.tables)}")
report.append("")
total_records = 0
for table_name, table in self.tables.items():
record_count = len(table['data'])
total_records += record_count
report.append(f"表: {table_name}")
report.append(f" 记录数: {record_count}")
report.append(f" 字段数: {len(table['columns'])}")
report.append(f" 字段: {', '.join(table['columns'].keys())}")
report.append("")
report.append(f"总记录数: {total_records}")
return "\n".join(report)
# 演示数据库操作
if __name__ == "__main__":
print("数据库管理系统演示:")
# 创建数据库管理器
db = DatabaseManager('demo.db')
# 1. 插入用户数据
print("\n1. 插入用户数据:")
user_data = [
{'username': 'alice', 'email': 'alice@example.com', 'age': 25},
{'username': 'bob', 'email': 'bob@example.com', 'age': 30},
{'username': 'charlie', 'email': 'charlie@example.com', 'age': 22}
]
for user in user_data:
db.insert_record('users', user)
# 2. 插入产品数据
print("\n2. 插入产品数据:")
product_data = [
{'name': 'Laptop', 'price': 999.99, 'category': 'Electronics', 'stock': 10},
{'name': 'Mouse', 'price': 29.99, 'category': 'Electronics', 'stock': 50},
{'name': 'Book', 'price': 19.99, 'category': 'Education', 'stock': 100}
]
for product in product_data:
db.insert_record('products', product)
# 3. 查询数据
print("\n3. 查询所有用户:")
users = db.select_records('users')
for user in users:
print(f" {user['username']} ({user['email']}) - {user['age']}岁")
print("\n4. 条件查询 - 年龄大于等于25的用户:")
older_users = db.select_records('users', conditions={'age': {'>=': 25}})
for user in older_users:
print(f" {user['username']} - {user['age']}岁")
print("\n5. 查询电子产品:")
electronics = db.select_records('products', conditions={'category': 'Electronics'})
for product in electronics:
print(f" {product['name']}: ${product['price']} (库存: {product['stock']})")
# 6. 更新数据
print("\n6. 更新数据 - 增加Laptop库存:")
db.update_records('products', {'name': 'Laptop'}, {'stock': 15})
# 7. 插入订单
print("\n7. 插入订单:")
order_data = [
{'user_id': 1, 'product_id': 1, 'quantity': 1, 'total_price': 999.99},
{'user_id': 2, 'product_id': 2, 'quantity': 2, 'total_price': 59.98}
]
for order in order_data:
db.insert_record('orders', order)
# 8. 查询所有订单
print("\n8. 查询所有订单:")
orders = db.select_records('orders')
for order in orders:
print(f" 订单 {order['id']}: 用户{order['user_id']} 购买产品{order['product_id']} x{order['quantity']} = ${order['total_price']}")
# 9. 表信息
print("\n9. 数据库表信息:")
for table_name in db.list_tables():
info = db.get_table_info(table_name)
print(f" {table_name}: {info['record_count']} 条记录")
# 10. 生成报告
print("\n10. 数据库报告:")
report = db.generate_report()
print(report)
# 11. 备份数据库
print("\n11. 备份数据库:")
db.backup_database('demo_backup.json')
输出示例
数据库管理系统演示:
初始化数据库: demo.db
创建表: users
SQL: CREATE TABLE users (id INTEGER PRIMARY KEY, username TEXT UNIQUE NOT NULL, email TEXT UNIQUE NOT NULL, age INTEGER, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
创建表: products
SQL: CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price REAL NOT NULL, category TEXT, stock INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
创建表: orders
SQL: CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER, product_id INTEGER, quantity INTEGER NOT NULL, total_price REAL NOT NULL, order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
数据库初始化完成
1. 插入用户数据:
成功插入记录到表 users: {'username': 'alice', 'email': 'alice@example.com', 'age': 25, 'id': 1, 'created_at': '2024-01-15T10:40:15.123456'}
成功插入记录到表 users: {'username': 'bob', 'email': 'bob@example.com', 'age': 30, 'id': 2, 'created_at': '2024-01-15T10:40:15.124567'}
成功插入记录到表 users: {'username': 'charlie', 'email': 'charlie@example.com', 'age': 22, 'id': 3, 'created_at': '2024-01-15T10:40:15.125678'}
2. 插入产品数据:
成功插入记录到表 products: {'name': 'Laptop', 'price': 999.99, 'category': 'Electronics', 'stock': 10, 'id': 1, 'created_at': '2024-01-15T10:40:15.126789'}
成功插入记录到表 products: {'name': 'Mouse', 'price': 29.99, 'category': 'Electronics', 'stock': 50, 'id': 2, 'created_at': '2024-01-15T10:40:15.127890'}
成功插入记录到表 products: {'name': 'Book', 'price': 19.99, 'category': 'Education', 'stock': 100, 'id': 3, 'created_at': '2024-01-15T10:40:15.128901'}
3. 查询所有用户:
查询表 users 返回 3 条记录
alice (alice@example.com) - 25岁
bob (bob@example.com) - 30岁
charlie (charlie@example.com) - 22岁
4. 条件查询 - 年龄大于等于25的用户:
查询表 users 返回 2 条记录
alice - 25岁
bob - 30岁
5. 查询电子产品:
查询表 products 返回 2 条记录
Laptop: $999.99 (库存: 10)
Mouse: $29.99 (库存: 50)
6. 更新数据 - 增加Laptop库存:
更新表 products 中 1 条记录
7. 插入订单:
成功插入记录到表 orders: {'user_id': 1, 'product_id': 1, 'quantity': 1, 'total_price': 999.99, 'id': 1, 'created_at': '2024-01-15T10:40:15.132345'}
成功插入记录到表 orders: {'user_id': 2, 'product_id': 2, 'quantity': 2, 'total_price': 59.98, 'id': 2, 'created_at': '2024-01-15T10:40:15.133456'}
8. 查询所有订单:
查询表 orders 返回 2 条记录
订单 1: 用户1 购买产品1 x1 = $999.99
订单 2: 用户2 购买产品2 x2 = $59.98
9. 数据库表信息:
users: 3 条记录
products: 3 条记录
orders: 2 条记录
10. 数据库报告:
============================================================
数据库报告: demo.db
============================================================
生成时间: 2024-01-15 10:40:15
表数量: 3
表: users
记录数: 3
字段数: 5
字段: id, username, email, age, created_at
表: products
记录数: 3
字段数: 6
字段: id, name, price, category, stock, created_at
表: orders
记录数: 2
字段数: 6
字段: id, user_id, product_id, quantity, total_price, order_date
总记录数: 8
11. 备份数据库:
数据库已备份到: demo_backup.json
知识点总结
- 数据库设计: 表结构设计、字段类型定义、约束条件
- CRUD操作: 创建(Create)、读取(Read)、更新(Update)、删除(Delete)
- 数据验证: 必需字段检查、唯一性约束、数据类型验证
- 查询优化: 条件过滤、排序、分页限制
- 数据备份: JSON格式数据导出和恢复
- 异常处理: 数据库操作异常捕获和处理
- 报告生成: 数据库状态统计和报告输出
扩展功能
- 索引支持: 为常用查询字段添加索引
- 事务处理: 支持数据库事务的提交和回滚
- 连接查询: 支持多表关联查询
- 数据迁移: 支持数据库结构变更和数据迁移
- 性能监控: 查询性能统计和优化建议
-
希望对初学者有帮助;致力于办公自动化的小小程序员一枚
-
希望能得到大家的【❤️一个免费关注❤️】感谢!
-
求个 🤞 关注 🤞 +❤️ 喜欢 ❤️ +👍 收藏 👍
-
此外还有办公自动化专栏,欢迎大家订阅:Python办公自动化专栏
-
此外还有爬虫专栏,欢迎大家订阅:Python爬虫基础专栏
-
此外还有Python基础专栏,欢迎大家订阅:Python基础学习专栏