本文介绍了Postgres / psycopg2-插入字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Postgres 9和Python 2.7.2与psycopg2一起使用,并试图插入带有正确转义引号的字符串值数组。示例:

I'm using Postgres 9 and Python 2.7.2 along with psycopg2 and am trying to insert an array of string values with properly escaped quotation marks. Sample:

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

cur.execute("insert into meta values ('%s');" % metadata)

引发异常:

psycopg2.ProgrammingError: syntax error at or near "One"
LINE 1: "Details": "['One...
                      ^

我也尝试过使用Postgres的E来逃避反斜杠,但是还没有找到正确的组合。

I've also tried using Postgres' E to escape along with backslashes, but haven't found the correct combination yet. Ideas?

推荐答案

您必须让psycopg为您做参数绑定:不要尝试自己引用它们。

You have to let psycopg do parameters binding for you: don't try to quote them yourself.

Psycopg自动转换python列表字符串转换为postgres数组。请检查

Psycopg automatically converts a python list of strings into a postgres array. Check http://initd.org/psycopg/docs/usage.html

这篇关于Postgres / psycopg2-插入字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 15:47