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.
70 lines
2.6 KiB
70 lines
2.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:
|
||
|
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 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()
|