简体   繁体   English

使用 python panda 模块附加到 sql 表

[英]Appending to a sql table using python panda module

I am attempting to append to a SQL table using to_sql command in python.我正在尝试使用 python 中的 to_sql 命令附加到 SQL 表。 Everything works fine but if I run my command more tahn once it will obviously append the same data.一切正常,但是如果我再次运行我的命令,它显然会附加相同的数据。 I know this could be solved with if_exists='replace' but when i do that i get the following error.我知道这可以通过 if_exists='replace' 解决,但是当我这样做时,我收到以下错误。

ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Column 'AccountName' in table 'table' is of a type that is invalid for use as a key column in an index. (1919) (SQLExecDirectW)") [SQL: u'CREATE INDEX [ix_table_AccountName] ON table ([AccountName])'] ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server] 表 'table' 中的列 'AccountName' 是一种不能用作键的类型索引中的列。(1919) (SQLExecDirectW)") [SQL: u'CREATE INDEX [ix_table_AccountName] ON table ([AccountName])']

I need to figure out how to either,only append data that is not already in the table, delete the data I am about to append if it is already in the table or how to fix my index problem so i can use if_exists='replace'我需要弄清楚如何仅附加表中尚未存在的数据,删除我即将附加的数据(如果它已经在表中)或如何解决我的索引问题,以便我可以使用 if_exists='replace '

engine = create_engine('mssql+pyodbc://UN:PW@DB')
df.to_sql("table", engine,if_exists='replace')

Your column 'AccountName' is probably too long.您的“AccountName”列可能太长了。 For MSSQL the index can only be 900 bytes, so if you use utf-8 this is 450 chars.对于 MSSQL,索引只能是 900 字节,因此如果您使用 utf-8,这是 450 个字符。

Try setting the dtype for your column in the to_sql() statement with a shorter length if that column is used as index.如果该列用作索引,请尝试在to_sql()语句中为您的列设置较短的长度。

from sqlalchemy.types import String
[...]
df.to_sql(
[...]
    dtype={
       [...]
       'AccountName': String(255),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM