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: cursor.execute("delete from {}".format("books")) insert_query = """ INSERT INTO {table_name} (name, url, star, star_people, author, translater, publisher, pub_year, price, comment) 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() 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: cursor.execute(f"SELECT * FROM {self.table_name} WHERE name LIKE '%{name}%' or author LIKE '%{name}%' ") book_list = cursor.fetchall() return book_list self.connection.commit() self.close() def login(self,username): with self.connection.cursor() as cursor: cursor.execute(f"SELECT * FROM {self.table_name} WHERE username='{username}'") user_list=cursor.fetchall() print(user_list) if len(user_list) >0: return user_list[0] else: return False self.connection.commit() self.close() 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()