相关疑难解决方法(0)

Postgres/psycopg2 - 插入字符串数组

我正在使用Postgres 9和Python 2.7.2以及psycopg2,并尝试使用正确转义的引号插入字符串值数组.样品:

metadata = {"Name": "Guest", "Details": "['One', 'Two', 'Three']"}

cur.execute("insert into meta values ('%s');" % metadata)
Run Code Online (Sandbox Code Playgroud)

抛出异常:

psycopg2.ProgrammingError: syntax error at or near "One"
LINE 1: "Details": "['One...
                      ^
Run Code Online (Sandbox Code Playgroud)

我也尝试使用Postgres'E与反斜杠一起逃脱,但还没有找到正确的组合.想法?

python postgresql psycopg2

12
推荐指数
2
解决办法
2万
查看次数

将快速熊猫数据帧写入postgres

我想知道从pandas DataFrame到postges DB中的数据写入数据的最快方法.

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()
Run Code Online (Sandbox Code Playgroud)

但它返回空列表[].

所以我有两个问题:将数据从python代码(数据帧)复制到postgres DB的最快方法是什么?我试过的第二种方法有什么不对?

python postgresql copy dataframe

4
推荐指数
1
解决办法
4724
查看次数

标签 统计

postgresql ×2

python ×2

copy ×1

dataframe ×1

psycopg2 ×1