我正在努力解决一个小问题,我正在尝试使用 Python sqlalchemy 在 MySQL 中创建一个表,该表将表创建到数据库中,但没有将行插入其中。下面是代码。有什么错误吗?
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine("mysql://root:1234@localhost:3306/paintings")
connection = engine.connect()
df = pd.read_csv("./data/artist.csv")
df.to_sql("artist", con=connection, index=False, if_exists="replace")
使用
if_exists
将 replace
参数更改为 append
。当您将其设置为 replace
时,如果表存在,它将替换该表,但不会插入数据。当设置为append
时,会将数据添加到现有表中,如果不存在则创建表。
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine("mysql://root:1234@localhost:3306/paintings")
connection = engine.connect()
df = pd.read_csv("./data/artist.csv")
df.to_sql("artist", con=connection, index=False, if_exists="append")