繁体   English   中英

使用python在redshift(或postgresql)中插入字典字符串。 逃生问题?

[英]Inserting a dict string in redshift (or postgresql) using python. Escape Issue?

通过python 3.6在redshift(或postgresql)中插入一个充满单引号的字符串时,我确实遇到了问题。

这是我的输入:

In[330]: out

Out[330]: 

"{'hourday': [17, 12, 18, 16], 'domain': ['google.ca', 'allrecipes.com'], 'device_type_id': [20], 'city': [90, 23, 42, 42]}"

这是一个字符串,由于以下查询,我尝试了多种方式将其插入数据库中:

cursor.execute("insert into table1 (message) VALUES (%s)",(out,))

我得到了:

"psycopg2.InternalError: current transaction is aborted, commands ignored until end of transaction block". 

我几乎尝试了所有修复此问题的方法:用双单引号替换单引号(以在sql中转义单引号),在Python中将反斜杠转义。 但是每一次,sql或python都会出现问题。 在某个时候,我什至有:

TypeError: not all arguments converted during string formatting

它在杀了我,请帮助我!

谢谢 !

编辑:发现了问题。 与我的数据库的连接实际上已被切断。我刷新了它,代码工作了。 谢谢 !

我无法使用本地postgres实例重现它:

conn = psycopg2.connect(host=DB_HOST, port=DB_PORT, user=DB_USER, password=DB_PASSWORD)
cursor = conn.cursor()
cursor.execute('CREATE TEMPORARY TABLE table1(message VARCHAR(1000)) ON COMMIT DELETE ROWS')
out = "\"{'hourday': [17, 12, 18, 16], 'domain': ['google.ca', 'allrecipes.com'], 'device_type_id': [20], 'city': [90, 23, 42, 42]}\""
cursor.execute('INSERT INTO table1 (message) VALUES (%s)', (out,))
cursor.execute('SELECT * from table1')
row = cursor.fetchone()
print(row[0])

没有问题的作品。 您正在使用哪个驱动程序?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM