Python图书管理系统
时间: 2024-01-07 12:22:56 浏览: 148
图书管理系统 Python实现
根据提供的引用内容,有两种实现Python图书管理系统的方法:
方法一:使用PyCharm和SQLite实现图书管理系统
```python
# 引入必要的库
import sqlite3
# 连接到数据库
conn = sqlite3.connect('library.db')
c = conn.cursor()
# 创建图书表
c.execute('''CREATE TABLE IF NOT EXISTS books
(id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
author TEXT,
year INTEGER)''')
# 添加图书
def add_book(title, author, year):
c.execute("INSERT INTO books (title, author, year) VALUES (?, ?, ?)", (title, author, year))
conn.commit()
# 删除图书
def delete_book(book_id):
c.execute("DELETE FROM books WHERE id=?", (book_id,))
conn.commit()
# 查询图书
def search_book(title):
c.execute("SELECT * FROM books WHERE title=?", (title,))
return c.fetchall()
# 修改图书信息
def update_book(book_id, title, author, year):
c.execute("UPDATE books SET title=?, author=?, year=? WHERE id=?", (title, author, year, book_id))
conn.commit()
# 关闭数据库连接
def close_connection():
conn.close()
# 示例代码
add_book("Python编程入门", "张三", 2021)
add_book("数据结构与算法", "李四", 2020)
delete_book(2)
update_book(1, "Python编程基础", "张三", 2022)
result = search_book("Python编程入门")
print(result)
# 关闭数据库连接
close_connection()
```
方法二:使用DTK+2.0和SQLite实现图书管理系统
```python
# 引入必要的库
import sqlite3
import dtk
# 连接到数据库
conn = sqlite3.connect('library.db')
c = conn.cursor()
# 创建图书表
c.execute('''CREATE TABLE IF NOT EXISTS books
(id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
author TEXT,
year INTEGER)''')
# 添加图书
def add_book(title, author, year):
c.execute("INSERT INTO books (title, author, year) VALUES (?, ?, ?)", (title, author, year))
conn.commit()
# 删除图书
def delete_book(book_id):
c.execute("DELETE FROM books WHERE id=?", (book_id,))
conn.commit()
# 查询图书
def search_book(title):
c.execute("SELECT * FROM books WHERE title=?", (title,))
return c.fetchall()
# 修改图书信息
def update_book(book_id, title, author, year):
c.execute("UPDATE books SET title=?, author=?, year=? WHERE id=?", (title, author, year, book_id))
conn.commit()
# 关闭数据库连接
def close_connection():
conn.close()
# 示例代码
add_book("Python编程入门", "张三", 2021)
add_book("数据结构与算法", "李四", 2020)
delete_book(2)
update_book(1, "Python编程基础", "张三", 2022)
result = search_book("Python编程入门")
print(result)
# 关闭数据库连接
close_connection()
```
阅读全文