我想知道最快的方式将数据从pandas DataFrame写到postgesdb中的表中。在
1)我试过pandas.to_sql
,但由于某种原因,需要实体来复制数据
2)除此之外,我还试过:
import io
f = io.StringIO()
pd.DataFrame({'a':[1,2], 'b':[3,4]}).to_csv(f)
cursor = conn.cursor()
cursor.execute('create table bbbb (a int, b int);COMMIT; ')
cursor.copy_from(f, 'bbbb', columns=('a', 'b'), sep=',')
cursor.execute("select * from bbbb;")
a = cursor.fetchall()
print(a)
cursor.close()
但它返回空列表[]
。在
所以我有两个问题:从python代码(dataframe)复制数据到postgres数据库的最快方法是什么?我尝试过的第二种方法有什么不对?在
你的第二种方法应该很快。在
您的代码有两个问题:
f
后,您将被定位到文件的末尾。在开始阅读之前,你需要把你的立场放回开头。在最后的代码应该是这样的:
相关问题 更多 >
编程相关推荐