You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
3.6 KiB

6 months ago
import pymysql
class BookDatabase:
def __init__(self, host, user, password, database, table_name):
self.host = host
self.user = user
self.password = password
self.database = database
self.table_name = table_name
def connect(self):
self.connection = pymysql.connect(host=self.host, user=self.user, password=self.password,
database=self.database, cursorclass=pymysql.cursors.DictCursor)
def close(self):
self.connection.close()
def table_exists(self):
with self.connection.cursor() as cursor:
check_table_query = f"SHOW TABLES LIKE '{self.table_name}'"
cursor.execute(check_table_query)
result = cursor.fetchone()
return bool(result)
def create_table(self):
with self.connection.cursor() as cursor:
create_table_query = """
CREATE TABLE IF NOT EXISTS books (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
url VARCHAR(255),
star FLOAT,
star_people INT,
author VARCHAR(255),
translater VARCHAR(255),
publisher VARCHAR(255),
pub_year VARCHAR(20),
price FLOAT,
comment TEXT
)
"""
cursor.execute(create_table_query)
self.connection.commit()
def insert_books(self, booklist):
with self.connection.cursor() as cursor:
6 months ago
cursor.execute("delete from {}".format("books"))
6 months ago
insert_query = """
6 months ago
INSERT INTO {table_name} (name, url, star, star_people, author, translater, publisher, pub_year, price, comment)
6 months ago
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
"""
for book in booklist:
cursor.execute(insert_query.format(table_name=self.table_name),
(book.name, book.url, float(book.star), int(book.star_people),
book.author, book.translater, book.publisher,
book.pub_year, float(book.price), book.comment))
self.connection.commit()
self.close()
6 months ago
def get_book_list(self,name=""):
with self.connection.cursor() as cursor:
if len(name.strip()) == 0:
cursor.execute(f"SELECT * FROM {self.table_name}")
book_list = cursor.fetchall()
return book_list
else:
6 months ago
cursor.execute(f"SELECT * FROM {self.table_name} WHERE name LIKE '%{name}%' or author LIKE '%{name}%' ")
6 months ago
book_list = cursor.fetchall()
return book_list
6 months ago
6 months ago
self.connection.commit()
self.close()
6 months ago
def login(self,username):
6 months ago
with self.connection.cursor() as cursor:
6 months ago
cursor.execute(f"SELECT * FROM {self.table_name} WHERE username='{username}'")
user_list=cursor.fetchall()
6 months ago
print(user_list)
6 months ago
if len(user_list) >0:
return user_list[0]
6 months ago
else:
return False
self.connection.commit()
self.close()
6 months ago
def initialize_table(self):
self.connect()
if not self.table_exists():
self.create_table()
# self.close()
# # 使用BookDatabase类
# db = BookDatabase(host='localhost', user='root', password='123456', database='xiaosuo', table_name='books')
# db.initialize_table()