你为什么要那样做?有一种更短的方法:中的
if_existskwag
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')


