图书管理系统借书还书Python程序
时间: 2023-12-24 19:24:57 浏览: 139
Python图书借阅系统(期末作品)
以下是一个简单的图书管理系统借书还书Python程序,它可以实现借书和还书的功能:
```python
import sqlite3
# 连接到数据库
conn = sqlite3.connect('library.db')
# 借书函数
def borrow_book():
book_id = input("请输入要借阅的书籍ID:")
user_id = input("请输入您的用户ID:")
cursor = conn.cursor()
# 查询书籍是否存在
cursor.execute("SELECT * FROM books WHERE id=?", (book_id,))
book = cursor.fetchone()
if book is None:
print("该书籍不存在!")
return
# 查询用户是否存在
cursor.execute("SELECT * FROM users WHERE id=?", (user_id,))
user = cursor.fetchone()
if user is None:
print("该用户不存在!")
return
# 查询用户是否已经借阅该书籍
cursor.execute("SELECT * FROM user_book WHERE user_id=? AND book_id=?", (user_id, book_id))
user_book = cursor.fetchone()
if user_book is not None:
print("您已经借阅了该书籍!")
return
# 更新用户借阅信息
cursor.execute("INSERT INTO user_book (user_id, book_id) VALUES (?, ?)", (user_id, book_id))
# 更新书籍库存信息
cursor.execute("UPDATE books SET stock=stock-1 WHERE id=?", (book_id,))
conn.commit()
print("借阅成功!")
# 还书函数
def return_book():
book_id = input("请输入要归还的书籍ID:")
user_id = input("请输入您的用户ID:")
cursor = conn.cursor()
# 查询书籍是否存在
cursor.execute("SELECT * FROM books WHERE id=?", (book_id,))
book = cursor.fetchone()
if book is None:
print("该书籍不存在!")
return
# 查询用户是否存在
cursor.execute("SELECT * FROM users WHERE id=?", (user_id,))
user = cursor.fetchone()
if user is None:
print("该用户不存在!")
return
# 查询用户是否已经借阅该书籍
cursor.execute("SELECT * FROM user_book WHERE user_id=? AND book_id=?", (user_id, book_id))
user_book = cursor.fetchone()
if user_book is None:
print("您没有借阅该书籍!")
return
# 更新用户借阅信息
cursor.execute("DELETE FROM user_book WHERE user_id=? AND book_id=?", (user_id, book_id))
# 更新书籍库存信息
cursor.execute("UPDATE books SET stock=stock+1 WHERE id=?", (book_id,))
conn.commit()
print("归还成功!")
# 主函数
def main():
while True:
print("欢迎使用图书管理系统!")
print("1. 借书")
print("2. 还书")
print("3. 退出")
choice = input("请选择操作:")
if choice == '1':
borrow_book()
elif choice == '2':
return_book()
elif choice == '3':
break
else:
print("无效的操作!")
# 关闭数据库连接
conn.close()
if __name__ == '__main__':
main()
```
阅读全文