编写程序实现对图书信息表的增删改查操作。 需求分析:现有图书信息表bookinfo(序号,图书编号,图书名称,作者,出版社,单价,出版日期,ISBN,库存数量)。写程序实现对该表的增删改查操作。
时间: 2024-12-29 16:30:30 浏览: 21
在编写程序实现对图书信息表的增删改查操作时,通常会使用结构化查询语言(SQL),因为它是数据库管理的标准语言。这里是一个简单的示例,我们将使用Python结合SQLite数据库来演示如何实现这个功能。假设我们已经有一个名为`BookInfo`的类表示图书信息,并创建了一个SQLite连接。
**1. 插入(增)操作:**
```python
class BookInfo:
def __init__(self, book_id, isbn, title, author, publisher, price, publication_date, stock):
self.book_id = book_id
self.isbn = isbn
self.title = title
self.author = author
self.publisher = publisher
self.price = price
self.publication_date = publication_date
self.stock = stock
def add_book(book_info):
conn = sqlite3.connect('library.db')
cursor = conn.cursor()
query = "INSERT INTO bookinfo VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
cursor.execute(query, (book_info.book_id, book_info.isbn, book_info.title, book_info.author, book_info.publisher, book_info.price, book_info.publication_date, book_info.stock))
conn.commit()
conn.close()
# 使用示例
add_book(BookInfo(1, '001', 'Python入门', '张三', '人民邮电出版社', 59.9, '2022-01-01', 100))
```
**2. 删除(减)操作:**
```python
def delete_book(isbn):
conn = sqlite3.connect('library.db')
cursor = conn.cursor()
query = "DELETE FROM bookinfo WHERE isbn = ?"
cursor.execute(query, (isbn,))
conn.commit()
conn.close()
```
**3. 更新(改)操作:**
```python
def update_book(book_id, field_name, new_value):
conn = sqlite3.connect('library.db')
cursor = conn.cursor()
query = f"UPDATE bookinfo SET {field_name} = ? WHERE book_id = ?"
cursor.execute(query, (new_value, book_id))
conn.commit()
conn.close()
```
**4. 查询(查)操作:**
```python
def get_books_by_author(author):
conn = sqlite3.connect('library.db')
cursor = conn.cursor()
query = "SELECT * FROM bookinfo WHERE author = ?"
cursor.execute(query, (author,))
books = cursor.fetchall()
conn.close()
return books
# 示例
books_by_author = get_books_by_author('张三')
```
阅读全文