Pandas to_sql doesn't insert any data in my table
我正在尝试在创建的表中插入一些数据。
我有一个看起来像这样的数据框:
我创建了一个表:
1 2 3 4 5 6 7 | create table online.ds_attribution_probabilities ( attribution_type text, channel text, date date , value float ) |
我正在运行此python脚本:
1 2 3 | engine = create_engine("postgresql://@e.eu-central-1.redshift.amazonaws.com:5439/mdhclient_encoding=utf8") connection = engine.raw_connection() result.to_sql('online.ds_attribution_probabilities', con=engine, index = False, if_exists = 'append') |
我没有收到任何错误,但是当我检查表中没有数据时。有什么事吗我是否必须提交或执行其他步骤?
尝试指定架构名称:
1 2 | result.to_sql('ds_attribution_probabilities', con=engine, schema='online', index=False, if_exists='append') |
希望这对其他人有帮助。如果传递连接对象,
方法,我也对其他假设相同
1 2 3 | con : sqlalchemy.engine.Engine or sqlite3.Connection Using SQLAlchemy makes it possible to use any DB supported by that library. Legacy support is provided for sqlite3.Connection objects. |
之所以得到我,是因为键入提示中指出
如果您与
在我的情况下,快速选项妨碍了将数据写入数据库。
为什么这不是快速加载干扰,我还没有弄清楚。
此代码无效:
1 2 | engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect={}".format(db_params), fast_executemany=True) df.to_sql('tablename', engine, index=False, schema = 'dbo', if_exists='replace' ) |
没有
检查
1 | engine.execute(text("SELECT my_mutating_procedure()").execution_options(autocommit=True)) |
由于我将sqlalchemy连接对象而不是引擎对象传递给con参数,因此造成了类似的问题。在我的情况下,表已创建但保留为空。
之所以会发生这种情况,是因为它默认为公共数据库,并且在公共数据库/架构下可能有一个名称相同的表,其中包含您的数据。
@MaxU的答案确实对某些人有所帮助,但对其他人却无济于事。
对于其他人,您可以尝试以下操作:
创建引擎时,请按以下方式指定架构名称:
1 2 | engine = create_engine(*<connection_string>*, connect_args={'options': '-csearch_path={}'.format(*<dbschema_name>*)}) |
链接:https://stackoverflow.com/a/49930672/8656608
使用
时遇到相同的问题
1 2 3 4 | with engine.connect() as conn, conn.begin(): dataframe.to_sql(name='table_name', schema='schema', con=conn, if_exists='append', index=False) conn.close() |
只需删除