
本教程详细讲解了在 python 中使用 sqlite3 动态创建子表的方法。针对数据抓取等场景中,根据主表记录动态生成关联子表的需求,文章指出了常见的sql语句格式化错误,并提供了正确的表名构建和动态创建子表的实践方法,确保数据库操作的成功与效率,同时探讨了相关的数据库设计考量。
在数据处理和爬虫应用中,我们经常会遇到需要为每一条主记录(例如,一个漫画系列)创建其关联的子记录(例如,该漫画的章节列表)的情况。虽然在大多数关系型数据库设计中,推荐使用外键关联的单个子表来存储这些数据,但在某些特定场景下,例如为了数据隔离、性能优化或简化查询逻辑,我们可能需要为每个主记录动态创建独立的子表。本教程将深入探讨如何在 Python 中利用 sqlite3 模块实现这一目标,并解决常见的动态表名构建问题。
假设我们有一个主表 Comics,存储了漫画的基本信息,如名称、封面URL和状态。现在,我们希望为每个漫画创建一个独立的子表,存储其所有章节的名称、发布日期和章节URL。这意味着如果 Comics 表中有100条记录,我们就需要动态创建100个子表,每个子表的名称与对应的漫画ID相关联,例如 ChildTable_1、ChildTable_2 等。
实现这一需求的关键挑战在于:
在尝试动态创建子表时,一个常见的错误是表名字符串格式化不当。例如,如果 cursor.fetchall() 返回的 ids 是一个包含元组的列表(如 [(1,), (2,)]),而我们直接尝试使用 ids[0] 进行格式化:
立即学习“Python免费学习笔记(深入)”;
# 假设 ids = [(1,), (2,)]
# 错误的尝试:
# for id_tuple in ids:
# # id_tuple 第一次迭代是 (1,)
# # ids[0] 始终是 (1,),而不是 1
# cursor.execute('''CREATE TABLE IF NOT EXISTS ChildTable_%s (...)''' % (ids[0]))这段代码的问题在于:
正确的做法是,在循环中,从当前迭代的元组中提取实际的 ID 值。
为了正确地动态创建子表,我们需要确保在构建表名时,使用从 cursor.fetchall() 结果中正确提取出的 ID 值。
以下是修正后的代码示例,展示了如何安全有效地动态创建子表:
import sqlite3
import requests
from bs4 import BeautifulSoup
import time # 推荐使用time模块,而不是直接导入sleep
# 模拟请求头,实际应用中应更完整
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
# 连接到 SQLite 数据库
connection = sqlite3.connect('parser_results.db')
cursor = connection.cursor()
# 创建主表 Comics (如果不存在)
cursor.execute('''
CREATE TABLE IF NOT EXISTS Comics (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
cover TEXT NOT NULL,
status TEXT NOT NULL,
comic_url TEXT UNIQUE NOT NULL
)
''')
connection.commit()
# 示例:爬取并插入 Comics 数据 (简化版,仅用于演示)
# 实际应用中,这部分代码应更健壮,包含错误处理和分页逻辑
def get_comic_urls_and_details():
base_url = "https://asuratoon.com/manga/?page={}&order=update"
for count in range(1, 2): # 仅爬取第一页作为示例
url = base_url.format(count)
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status() # 检查HTTP请求是否成功
soup = BeautifulSoup(response.text, "html.parser")
data_url = soup.find_all('div', class_='bsx')
for comic_div in data_url:
comic_link = comic_div.find('a')
if comic_link:
comic_url = comic_link.get('href')
# 进一步访问每个漫画详情页获取名称、封面和状态
detail_response = requests.get(comic_url, headers=headers, timeout=10)
detail_response.raise_for_status()
detail_soup = BeautifulSoup(detail_response.text, "html.parser")
data_general = detail_soup.find('div', class_='bixbox animefull')
if data_general:
name_tag = data_general.find('h1', class_='entry-title')
cover_tag = data_general.find('img')
status_div = data_general.find('div', class_='imptdt')
name = name_tag.text.strip() if name_tag else "Unknown Name"
cover = cover_tag.get('src') if cover_tag else "No Cover"
status = status_div.text.replace('Status ', '').strip() if status_div else "Unknown Status"
# 插入主表数据
try:
cursor.execute('INSERT INTO Comics (name, cover, status, comic_url) VALUES (?, ?, ?, ?)',
(name, cover, status, comic_url))
connection.commit()
print(f"Inserted comic: {name}")
except sqlite3.IntegrityError:
print(f"Comic '{name}' (URL: {comic_url}) already exists, skipping.")
except Exception as e:
print(f"Error inserting comic {name}: {e}")
time.sleep(1) # 礼貌性延时
except requests.exceptions.RequestException as e:
print(f"Error fetching URL {url}: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# 执行数据抓取和插入,确保Comics表有数据
get_comic_urls_and_details()
# 获取所有漫画的 ID 和 URL,以便后续创建子表和插入章节数据
cursor.execute('SELECT id, comic_url FROM Comics')
comic_data_for_children = cursor.fetchall() # 结果如 [(1, 'url1'), (2, 'url2')]
print(f"Found {len(comic_data_for_children)} comics to create child tables for.")
# 遍历每个漫画,创建对应的子表并插入章节数据
for comic_id, comic_detail_url in comic_data_for_children:
# 构建子表名称,确保ID是整数
child_table_name = f"ChildTable_{comic_id}"
# 使用 f-string 安全地构建 CREATE TABLE 语句
# 推荐使用方括号 [] 包裹表名,以防表名包含特殊字符(虽然这里是纯数字ID)
create_table_sql = f"""
CREATE TABLE IF NOT EXISTS [{child_table_name}] (
id INTEGER PRIMARY KEY AUTOINCREMENT,
chapter_name TEXT,
release_date TEXT,
chapter_url TEXT,
comic_id INTEGER NOT NULL,
FOREIGN KEY (comic_id) REFERENCES Comics(id)
);
"""
try:
cursor.execute(create_table_sql)
print(f"Created table: {child_table_name}")
connection.commit()
# 爬取当前漫画的章节信息并插入到对应的子表
# 假设章节信息可以在 comic_detail_url 页面找到
print(f"Fetching chapters for comic ID {comic_id} from {comic_detail_url}")
detail_response = requests.get(comic_detail_url, headers=headers, timeout=10)
detail_response.raise_for_status()
detail_soup = BeautifulSoup(detail_response.text, "html.parser")
chapters_data = detail_soup.find_all('div', class_='eph-num')
if not chapters_data:
print(f"No chapters found for comic ID {comic_id}.")
for chapter_item in chapters_data:
chapter_name_tag = chapter_item.find('span', class_='chapternum')
release_date_tag = chapter_item.find('span', class_='chapterdate')
chapter_url_tag = chapter_item.find('a')
chapter_name = chapter_name_tag.text.strip() if chapter_name_tag else "Unknown Chapter"
release_date = release_date_tag.text.strip() if release_date_tag else "Unknown Date"
chapter_url = chapter_url_tag.get('href') if chapter_url_tag else "No URL"
# 插入章节数据到对应的子表
insert_chapter_sql = f"""
INSERT INTO [{child_table_name}] (chapter_name, release_date, chapter_url, comic_id)
VALUES (?, ?, ?, ?);
"""
try:
cursor.execute(insert_chapter_sql, (chapter_name, release_date, chapter_url, comic_id))
connection.commit()
# print(f" Inserted chapter '{chapter_name}' into {child_table_name}")
except Exception as e:
print(f" Error inserting chapter '{chapter_name}' into {child_table_name}: {e}")
time.sleep(1) # 礼貌性延时
except requests.exceptions.RequestException as e:
print(f"Error fetching chapter details for {comic_detail_url}: {e}")
except Exception as e:
print(f"Error creating table or inserting data for comic ID {comic_id}: {e}")
# 关闭数据库连接
connection.close()
print("Database operations completed and connection closed.")关键修正点:
数据库设计考量:
SQL 注入风险: 尽管本例中表名是根据内部 ID 生成的,相对安全,但在实际应用中,如果动态生成的 SQL 语句(包括表名、列名等)包含来自用户输入的变量,必须采取严格的参数化查询或白名单验证,以防止 SQL 注入攻击。对于表名和列名,通常无法使用参数化查询,因此更应谨慎处理。
错误处理: 在实际的爬虫和数据库操作中,应包含健壮的错误处理机制(如 try-except 块),以应对网络请求失败、HTML 结构变化、数据库操作异常等情况。
连接管理: 确保在所有数据库操作完成后,调用 connection.commit() 提交事务,并调用 connection.close() 关闭数据库连接,释放资源。
通过本教程,我们学习了如何在 Python 中使用 sqlite3 模块动态创建子表。关键在于正确地从查询结果中提取 ID,并利用 f-string 等方式安全有效地构建 SQL CREATE TABLE 语句中的表名。尽管动态子表在某些特定场景下有用,但在大多数关系型数据库设计中,使用外键关联的单个子表是更推荐和更具可维护性的方法。在决定采用动态子表策略时,务必权衡其优缺点,并考虑未来的可扩展性和维护成本。
以上就是Python SQLite3 动态创建子表指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号