利用pandas + sqlalchemy读取实时更新csv文件,并导入到MySQL
时间: 2023-09-12 13:07:45 浏览: 257
可以按以下步骤实现:
1. 导入必要的库:pandas、sqlalchemy
``` python
import pandas as pd
from sqlalchemy import create_engine
```
2. 创建MySQL数据库连接
``` python
# 连接MySQL数据库
engine = create_engine('mysql+pymysql://root:password@localhost:3306/testDB')
```
3. 读取csv文件数据
``` python
# 读取csv文件数据
df = pd.read_csv('data.csv', encoding='utf-8')
```
4. 将数据导入到MySQL数据库
``` python
# 将数据导入到MySQL数据库
df.to_sql(name='data', con=engine, if_exists='replace', index=False)
```
完整代码示例:
``` python
import pandas as pd
from sqlalchemy import create_engine
# 连接MySQL数据库
engine = create_engine('mysql+pymysql://root:password@localhost:3306/testDB')
# 读取csv文件数据
df = pd.read_csv('data.csv', encoding='utf-8')
# 将数据导入到MySQL数据库
df.to_sql(name='data', con=engine, if_exists='replace', index=False)
```
以上代码将会在MySQL中创建名为"data"的表,并将csv文件中的数据导入到该表中。每次运行代码时,如果表已经存在,则会将原有数据删除并替换为新的数据。如果表不存在,则会自动创建。你也可以根据需要调整if_exists参数的值,例如"append"表示追加数据,"fail"表示如果表已经存在则不做任何操作。
阅读全文
相关推荐


















