如何使用Python和SQLAlchemy将CSV文件上传至新数据库表
问题描述
尝试使用Python和SQLAlchemy将CSV文件上传至新的数据库表,执行了以下操作:
- 执行安装命令:
! pip install mysqlclient - 编写并运行如下代码:
import pandas as pd from sqlalchemy import create_engine # Step 1: Read the CSV file into a DataFrame path = "baby_names_2021.csv" df = pd.read_csv(path) print(df.shape) # To check the shape of the DataFrame # Step 2: Create a connection to the database username = "username" password = "piece_of_pork" hostname = "ssss.mysql.pythonanywhere-services.com" databasename = "database" # Create the database engine engine = create_engine(f'mysql://{username}:{password}@{hostname}/{databasename}') # Step 3: Upload the DataFrame to the SQL table df.to_sql('baby_data', engine, if_exists='append', index=False)
运行后出现错误:NameError: name '_mysql' is not defined
解决方案
这个错误多由mysqlclient安装不完整或连接驱动配置问题导致,可按以下步骤解决:
1. 重新安装mysqlclient
先卸载现有版本,再重新安装,确保依赖完整:
pip uninstall -y mysqlclient pip install mysqlclient
如果是在PythonAnywhere环境中,需匹配对应Python版本的pip命令,比如pip3.10 install mysqlclient(根据你的实际Python版本调整)。
2. 切换至pymysql驱动
若mysqlclient仍无法正常工作,可改用纯Python实现的pymysql驱动,兼容性更强:
- 先安装pymysql:
pip install pymysql
- 修改代码中的引擎创建语句:
engine = create_engine(f'mysql+pymysql://{username}:{password}@{hostname}/{databasename}')
3. 检查版本兼容性
确保Python版本与依赖版本匹配:
- Python 3.10+建议使用mysqlclient 2.1.0及以上版本;
- 旧版Python需选择对应兼容的依赖版本。
内容的提问来源于stack exchange,提问作者elksie5000
相关产品推荐
相关产品推荐

