题目:
创建一个图书管理数据表,要求字段包括:
id,图书名、作者、价格、出版社,
其中id为主键自动增长,
图书名不能重复,并实现数据的增删改成基本操作
#拓展需求:添加书籍信息时录入的日期时间信息
实现方式:
使用sqlite3库操作sqlite数据库,实现简单的增删改查
#导入sqlite3库
import sqlite3
from datetime import datetime
# 连接到数据库,test.db
conn = sqlite3.connect('test.db')
# 创建游标
cur = conn.cursor()
# 编写打印表语句,设置字段
books = """
create table if not exists books (
id integer primary key autoincrement,
name text not null,
author text,
price real,
publisher text,
create_time text
)
"""
# 创建表
cur.execute(books)
# 增
def add_book():
sql1 = "insert into books (name, author, price, publisher, create_time) values (?,?,?,?,?)"
name = input("请输入图书名:")
if name not in [item[0] for item in cur.execute("select name from books")]:
author = input("请输入作者:")
price = float(input("请输入价格:"))
publisher = input("请输入出版社:")
create_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
data = (name, author, price, publisher, create_time)
cur.execute(sql1, data)
print("图书添加成功")
else:
print("图书已存在")
# 删
def delete_book():
sql2 = "delete from books where name =?"
book_name = input("请输入要删除的图书名:")
if book_name in [item[0] for item in cur.execute("select name from books")]:
data = (book_name,)
cur.execute(sql2, data)
print("图书删除成功")
else:
print("图书不存在")
# 改
def update_book():
sql3 = "update books set author =?, price =?, publisher =? where name =?"
book_name = input("请输入要修改的图书名:")
if book_name in [item[0] for item in cur.execute("select name from books")]:
author = input("请输入作者:")
price = float(input("请输入价格:"))
publisher = input("请输入出版社:")
data = (author, price, publisher, book_name)
cur.execute(sql3, data)
print("图书信息修改成功")
else:
print("图书不存在")
# 查
def show_book():
sql4 = "select * from books"
cur.execute(sql4)
result = cur.fetchall()
for item in result:
print(item)
# 最后记得提交和关闭
conn.commit()
conn.close()
代码实现