帮我写一个用python和SQLserver建立的图书管理系统,可以实现书籍的信息查询和借阅者的信息查询,同时会对超期不还的读者进行罚款,可以实现管理员对书籍信息的更新
时间: 2024-04-08 13:29:16 浏览: 60
当然可以帮你写一个图书管理系统。首先,你需要安装Python和SQL Server,并确保已经设置好了数据库连接。
下面是一个简单的示例,展示如何使用Python和SQL Server来建立一个图书管理系统:
```python
import pyodbc
# 连接到SQL Server数据库
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=<server_name>;DATABASE=<database_name>;UID=<username>;PWD=<password>')
# 创建游标
cursor = conn.cursor()
# 创建图书表
cursor.execute('''
CREATE TABLE books (
id INT PRIMARY KEY,
title VARCHAR(255),
author VARCHAR(255),
availability BIT
)
''')
# 创建读者表
cursor.execute('''
CREATE TABLE borrowers (
id INT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255),
fine DECIMAL(10, 2)
)
''')
# 添加书籍信息
cursor.execute("INSERT INTO books (id, title, author, availability) VALUES (1, 'Book 1', 'Author 1', 1)")
cursor.execute("INSERT INTO books (id, title, author, availability) VALUES (2, 'Book 2', 'Author 2', 1)")
cursor.execute("INSERT INTO books (id, title, author, availability) VALUES (3, 'Book 3', 'Author 3', 0)")
# 添加读者信息
cursor.execute("INSERT INTO borrowers (id, name, email, fine) VALUES (1, 'Borrower 1', 'borrower1@example.com', 0)")
cursor.execute("INSERT INTO borrowers (id, name, email, fine) VALUES (2, 'Borrower 2', 'borrower2@example.com', 10.50)")
cursor.execute("INSERT INTO borrowers (id, name, email, fine) VALUES (3, 'Borrower 3', 'borrower3@example.com', 5.25)")
# 提交事务
conn.commit()
# 书籍信息查询
def search_book(title):
cursor.execute(f"SELECT * FROM books WHERE title LIKE '%{title}%'")
books = cursor.fetchall()
if not books:
print("未找到相关书籍")
else:
for book in books:
print(f"ID: {book.id}, 标题: {book.title}, 作者: {book.author}, 可借状态: {'可借' if book.availability else '不可借'}")
# 读者信息查询
def search_borrower(name):
cursor.execute(f"SELECT * FROM borrowers WHERE name LIKE '%{name}%'")
borrowers = cursor.fetchall()
if not borrowers:
print("未找到相关读者")
else:
for borrower in borrowers:
print(f"ID: {borrower.id}, 姓名: {borrower.name}, 邮箱: {borrower.email}, 罚款金额: {borrower.fine}")
# 超期罚款
def fine_borrower(borrower_id, amount):
cursor.execute(f"UPDATE borrowers SET fine = fine + {amount} WHERE id = {borrower_id}")
conn.commit()
print("罚款成功")
# 更新书籍信息
def update_book(book_id, title, author, availability):
cursor.execute(f"UPDATE books SET title = '{title}', author = '{author}', availability = {availability} WHERE id = {book_id}")
conn.commit()
print("书籍信息更新成功")
# 测试功能
search_book("Book")
search_borrower("Borrower")
fine_borrower(1, 5.50)
update_book(2, "Updated Book", "Updated Author", 0)
# 关闭连接
conn.close()
```
上述代码是一个简单的示例,演示了如何使用Python和SQL Server来建立一个图书管理系统。你可以根据自己的需求进行修改和扩展。请确保在使用之前替换 `<server_name>`, `<database_name>`, `<username>`, `<password>` 为你的实际数据库连接信息。
注意:这只是一个简单的示例,实际的图书管理系统可能需要更多的功能和复杂性,例如借书、还书、预订等功能。你可以根据自己的需求进一步扩展这个系统。
阅读全文