如何在Python中将DataFrame结果插入SQL表指定列imgtext
问题描述
我有一个DataFrame结果,需要逐行插入到现有SQL表中,想了解如何将结果插入名为imgtext的指定列。已知对应的SQL语句写法为:
INSERT INTO tableName(imgtext) VALUES('Learn MySQL INSERT Statement');
现有Python脚本功能:
- 从csv读取数据,借助BeautifulSoup处理后得到结果;
- 目前会将结果保存到csv。
现在不想保存到csv,而是把结果插入SQL表的imgtext列,需求是如何通过DataFrame处理csv数据,将结果插入SQL而非保存到CSV。
现有代码:
img_text_list = [] df1 = pd.DataFrame( columns=['imgtext']) img_formats = [".jpg", ".jpeg"] df = pd.read_csv("urls.csv") urls = df["urls"].tolist() for y in urls: response = requests.get(y) soup = BeautifulSoup(response.text, 'html.parser') img_tags = soup.find_all('img', class_='pick') img_srcs = ["https://myimpact.in/" + img['src'].replace( '\\', '/') if img.has_attr('src') else '-' for img in img_tags] for count, x in enumerate(img_srcs): if x != '-': if pathlib.Path(x).suffix in img_formats: response = requests.get(x) img = Image.open(io.BytesIO(response.content)) text = pt.image_to_string(img, lang="hin") # how to insert this text value into sql table column name - imgtext img_text_list.append(text) df1['img_text'] = img_text_list df1.to_csv('data.csv', encoding='utf-8')
解决方案
方法一:用pandas的to_sql批量插入(推荐)
这是最简洁高效的方式,直接把DataFrame写入SQL表,不用手动拼接SQL语句。
操作步骤:
- 先安装对应的数据库连接库:MySQL用
mysql-connector-python或pymysql,PostgreSQL用psycopg2,SQLite无需额外安装。 - 创建数据库连接引擎(以MySQL为例)。
- 调整DataFrame的列名与SQL表的列名对应,调用
to_sql插入数据。
修改后的完整代码:
import pandas as pd import requests from bs4 import BeautifulSoup import pathlib import io from PIL import Image import pytesseract as pt from sqlalchemy import create_engine # 需安装sqlalchemy:pip install sqlalchemy # 数据库连接配置(根据你的数据库类型修改) # MySQL示例:替换为你的实际信息 engine = create_engine('mysql+pymysql://用户名:密码@主机地址:端口/数据库名') # SQLite示例: # engine = create_engine('sqlite:///your_database.db') img_text_list = [] img_formats = [".jpg", ".jpeg"] df = pd.read_csv("urls.csv") urls = df["urls"].tolist() for y in urls: response = requests.get(y) soup = BeautifulSoup(response.text, 'html.parser') img_tags = soup.find_all('img', class_='pick') img_srcs = ["https://myimpact.in/" + img['src'].replace('\\', '/') if img.has_attr('src') else '-' for img in img_tags] for x in img_srcs: if x != '-' and pathlib.Path(x).suffix in img_formats: response = requests.get(x) img = Image.open(io.BytesIO(response.content)) text = pt.image_to_string(img, lang="hin") img_text_list.append(text) # 构造与SQL表列名匹配的DataFrame df1 = pd.DataFrame({'imgtext': img_text_list}) # 批量插入到SQL表,替换tableName为你的实际表名 # if_exists='append'表示追加数据,不会清空原有表 df1.to_sql(name='tableName', con=engine, if_exists='append', index=False)
方法二:逐行执行INSERT语句(适合自定义逻辑的场景)
如果需要逐行处理或有自定义插入逻辑,可以直接用数据库连接执行SQL语句。
修改后的代码片段(替换原代码末尾保存csv的部分):
import mysql.connector # 以MySQL为例,需安装:pip install mysql-connector-python # 建立数据库连接,替换为你的实际信息 conn = mysql.connector.connect( host='主机地址', user='用户名', password='密码', database='数据库名' ) cursor = conn.cursor() # 逐行插入数据,使用参数化查询防止SQL注入 for text in img_text_list: sql = "INSERT INTO tableName(imgtext) VALUES(%s)" cursor.execute(sql, (text,)) # 提交事务并关闭连接 conn.commit() cursor.close() conn.close()
注意事项:
- 所有占位符(用户名、密码、主机地址、数据库名、tableName)需替换为你的实际信息。
- 必须使用参数化查询,禁止直接拼接字符串到SQL语句中,避免SQL注入风险。
- 数据量较大时优先使用
to_sql批量插入,效率远高于逐行插入。
内容的提问来源于stack exchange,提问作者jeniffer
相关产品推荐
相关产品推荐

