无法使用SQLAlchemy将熊猫to_sql中的表删除
问题内容:
我正在尝试删除现有表,执行查询,然后使用pandas
to_sql函数重新创建表。此查询在pgadmin中有效,但在此处无效。有任何想法是熊猫错误还是我的代码错误?
具体错误是 ValueError: Table 'a' already exists.
import pandas.io.sql as psql
from sqlalchemy import create_engine
engine = create_engine(r'postgresql://user@localhost:port/dbname')
c = engine.connect()
conn = c.connection
sql = """
drop table a;
select * from some_table limit 1;
"""
df = psql.read_sql(sql, con=conn)
print df.head()
df.to_sql('a', engine)
conn.close()
问题答案:
你为什么要那样做?有一种更短的方法:中的if_exists
kwag to_sql
。尝试这个:
import pandas.io.sql as psql
from sqlalchemy import create_engine
engine = create_engine(r'postgresql://user@localhost:port/dbname')
c = engine.connect()
conn = c.connection
sql = """
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 argument
df.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 pd
from sqlalchemy import create_engine
engine = 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')