1、语法
df.to_sql(name='tablename', con=engine, if_exists='replace', index=False)
- name:表名
- con:数据库连接
- if_exists:表已经存在时的行为,可以选择'fail'、'replace'或'append'
'fail'
(默认值):如果目标表已经存在,将会抛出一个ValueError
异常,写入操作会失败,不会覆盖或追加数据。'replace'
:如果目标表已经存在,将会先删除目标表,然后再将数据写入新表,相当于完全替换目标表。'append'
:如果目标表已经存在,将会向目标表中追加新数据,保留已有数据。
- index:是否包含索引列
True
:将索引列写入数据库表。False
:不将索引列写入数据库表。
2、示例
import pandas as pd
from sqlalchemy import create_engine
# 创建一个DataFrame
data = {
'id': [1, 2, 3],
'name': ['Alice', 'Bob', 'Charlie']
}
df = pd.DataFrame(data)
# 建立与SQLite数据库的连接
engine = create_engine('sqlite:///my_database.db')
# 使用to_sql()方法将数据插入到数据库中
df.to_sql('my_table', engine, if_exists='replace', index=False)
评论列表,共 0 条评论
暂无评论