请帮我写一个图书管理系统的代码
时间: 2023-08-20 07:37:58 浏览: 92
好的,以下是一个简单的图书管理系统的代码,基于Python语言和SQLite数据库:
```python
import sqlite3
# 连接数据库
conn = sqlite3.connect('library.db')
cursor = conn.cursor()
# 创建图书表
cursor.execute('''CREATE TABLE IF NOT EXISTS books
(id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
author TEXT,
publisher TEXT,
publish_date TEXT,
isbn TEXT,
price REAL,
count INTEGER)''')
# 添加图书
def add_book(title, author, publisher, publish_date, isbn, price, count):
cursor.execute("INSERT INTO books (title, author, publisher, publish_date, isbn, price, count) VALUES (?, ?, ?, ?, ?, ?, ?)",
(title, author, publisher, publish_date, isbn, price, count))
conn.commit()
# 删除图书
def delete_book(id):
cursor.execute("DELETE FROM books WHERE id = ?", (id,))
conn.commit()
# 修改图书信息
def update_book(id, title, author, publisher, publish_date, isbn, price, count):
cursor.execute("UPDATE books SET title=?, author=?, publisher=?, publish_date=?, isbn=?, price=?, count=? WHERE id=?",
(title, author, publisher, publish_date, isbn, price, count, id))
conn.commit()
# 查询图书列表
def search_books():
cursor.execute("SELECT * FROM books")
books = cursor.fetchall()
for book in books:
print(book)
# 查询图书详情
def search_book(id):
cursor.execute("SELECT * FROM books WHERE id=?", (id,))
book = cursor.fetchone()
if book:
print(book)
else:
print("未找到该图书")
# 测试代码
if __name__ == '__main__':
add_book("Python编程从入门到实践", "Eric Matthes", "人民邮电出版社", "2016-11-01", "978-7-115-43183-2", 79.00, 10)
add_book("流畅的Python", "Luciano Ramalho", "人民邮电出版社", "2018-10-01", "978-7-115-46546-4", 89.00, 5)
search_books()
search_book(1)
update_book(1, "Python编程:从入门到实践", "Eric Matthes", "人民邮电出版社", "2016-11-01", "978-7-115-43183-2", 79.00, 20)
search_book(1)
delete_book(2)
search_books()
# 关闭数据库连接
conn.close()
```
这个代码实现了图书的添加、删除、修改、查询等功能,并使用SQLite数据库存储数据。在运行代码之前需要先安装SQLite库和Python环境。
阅读全文