你为什么要这样做?有一个更短的方法:if_exists
夸格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()
根据docs:
替换:如果表存在,则删除它,重新创建它,然后插入数据。
诗。附加提示:
这是处理连接的更好方法:
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')