我想向现有的sqlite(或mysql)表中写入数据框,有时该数据框将包含数据库中尚不存在的新列。为了避免这种错误,我需要怎么做?有没有办法告诉pandas或sqlalchemy用潜在的新列自动扩展数据库表?
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) table match_exact_both has no column named ....
Run Code Online (Sandbox Code Playgroud)
spa*_*row 13
这是我使用 mySQL 和 sqlalchemy 的解决方案。基本思想是,如果可能的话,我想附加到 SQL 数据库而不是重写整个内容,但是如果有一个新列,那么我可以在 Pandas 中合并数据,然后覆盖现有数据库。
import pymysql
from sqlalchemy import create_engine
import pandas as pd
cnx = create_engine('mysql+pymysql://username:password@hostname/database_name')
try:
#this will fail if there is a new column
df.to_sql(name='sql_table', con=cnx, if_exists = 'append', index=False)
except:
data = pd.read_sql('SELECT * FROM sql_table', cnx)
df2 = pd.concat([data,df])
df2.to_sql(name='sql_table', con=cnx, if_exists = 'replace', index=False)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1626 次 |
| 最近记录: |