简体   繁体   English

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

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

I do have a problem with inserting a string full of single quotes in my redshift (or postgresql) through python 3.6. 通过python 3.6在redshift(或postgresql)中插入一个充满单引号的字符串时,我确实遇到了问题。

Here's my input: 这是我的输入:

In[330]: out

Out[330]: 

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

It's a string and I tried by many means to insert it in my database thanks to this query: 这是一个字符串,由于以下查询,我尝试了多种方式将其插入数据库中:

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

I get a : 我得到了:

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

I tried almost everything to fix it : replacing single quotes with double single quotes (to escape single quotes in sql), putting backslash to escape in python. 我几乎尝试了所有修复此问题的方法:用双单引号替换单引号(以在sql中转义单引号),在Python中将反斜杠转义。 But every single time, there was a problem or with sql or with python. 但是每一次,sql或python都会出现问题。 At some point I even had a : 在某个时候,我什至有:

TypeError: not all arguments converted during string formatting

It's killing me, please help me ! 它在杀了我,请帮助我!

Thank you ! 谢谢 !

EDIT : Found the problem. 编辑:发现了问题。 The connection with my database was actually cut... I refreshed it and the code worked. 与我的数据库的连接实际上已被切断。我刷新了它,代码工作了。 Thank you ! 谢谢 !

I can't reproduce it with a local postgres instance: 我无法使用本地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])

Works without problems. 没有问题的作品。 Which driver are you using? 您正在使用哪个驱动程序?

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

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