栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

无法使用SQLAlchemy将熊猫to_sql中的表删除

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

无法使用SQLAlchemy将熊猫to_sql中的表删除

你为什么要那样做?有一种更短的方法:中的

if_exists
kwag
to_sql
。尝试这个:

import pandas.io.sql as psqlfrom sqlalchemy import create_engineengine = create_engine(r'postgresql://user@localhost:port/dbname')c = engine.connect()conn = c.connectionsql = """select * from some_table limit 1;"""df = psql.read_sql(sql, con=conn)print df.head()# Notice how below line is different. You forgot the schema argumentdf.to_sql('a', con=conn, schema=schema_name, if_exists='replace')conn.close()

根据文档:

replace:如果存在表,则将其删除,重新创建并插入数据。


附言 附加提示:

这是处理连接的更好方法:

with engine.connect() as conn, conn.begin():    sql = """select * from some_table limit 1"""    df = psql.read_sql(sql, con=conn)    print df.head()    df.to_sql('a', con=conn, schema=schema_name, if_exists='replace')

因为它可以确保连接始终关闭,即使您的程序因错误退出。这对于防止数据损坏很重要。此外,我将使用以下代码:

import pandas as pd...pd.read_sql(sql, conn)

而不是您的操作方式。

因此,如果我在您的位置编写该代码,它将看起来像这样:

import pandas as pdfrom sqlalchemy import create_engineengine = create_engine(r'postgresql://user@localhost:port/dbname')with engine.connect() as conn, conn.begin():    df = pd.read_sql('select * from some_table limit 1', con=conn)    print df.head()    df.to_sql('a', con=conn, schema=schema_name, if_exists='replace')


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611513.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号