pandas to_sql pandas方法改变sqlite表的scheme

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24064509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:08:02  来源:igfitidea点击:

to_sql pandas method changes the scheme of sqlite tables

pythonpandas

提问by drastega

When I write Pandas DataFrame to my SQLite database using to_sqlmethod it changes the .schemaof my table even if I use if_exists='append'. For example after execution

当我使用to_sql方法将 Pandas DataFrame 写入我的 SQLite 数据库时.schema,即使我使用if_exists='append'. 例如执行后

with sqlite3.connect('my_db.sqlite') as cnx:
    df.to_sql('Resolved', cnx, if_exists='append')

original .schema:

原文.schema

CREATE TABLE `Resolved` (
`Name` TEXT NOT NULL COLLATE NOCASE,
`Count` INTEGER NOT NULL,
`Obs_Date` TEXT NOT NULL,
`Bessel_year` REAL NOT NULL,
`Filter` TEXT NOT NULL,
`Comments` TEXT COLLATE NOCASE
);

changes to:

更改为:

CREATE TABLE Resolved (
                  [Name] TEXT,
  [Count] INTEGER,
  [Obs_Date] TEXT,
  [Bessel_year] REAL,
  [Filter] TEXT,
  [Comments] TEXT

                  );

How to save the original scheme of my table? I use pandas 0.14.0, Python 2.7.5

如何保存我的表的原始方案?我使用Pandas 0.14.0,Python 2.7.5

回答by joris

Starting from 0.14 (what you are using), the sql functions are refactored to use sqlalchemyto improve the functionality`. See the whatsnewand docson this.
The raw sqlite3 connection is still supported as a fallback (but that is the only sql flavor that is supported without sqlalchemy).

从 0.14(您正在使用的)开始,sql 函数被重构以用于sqlalchemy改进功能` 。见whatsnew文档这一点。
仍然支持原始 sqlite3 连接作为后备(但这是唯一不支持 sqlalchemy 的 sql 风格)。

Using sqlalchemy should solve the issue. For this you can just create a sqlalchemy engine instead of the direct sqlite connection cnx:

使用 sqlalchemy 应该可以解决这个问题。为此,您可以创建一个 sqlalchemy 引擎而不是直接的 sqlite 连接cnx

engine = sqlalchemy.create_engine('sqlite:///my_db.sqlite')
df.to_sql('Resolved', engine, if_exists='append')

But I filed an issue for the case with the sqlite cnx fallback option: https://github.com/pydata/pandas/issues/7355

但是我使用 sqlite cnx 回退选项为该案例提交了一个问题:https: //github.com/pydata/pandas/issues/7355