类型错误:参数 1 必须是字符串或 unicode 对象 [英] TypeError: argument 1 must be a string or unicode object
问题描述
使用此查询:
04/25/2017 00:42:28.180 INFO (u"UPDATE posts SET translated_text='Unroll.me CEO dice que es "desgarrador" que los usuarios se molesten Unroll.me vendi\xf3 sus datos de correo electr\xf3nico anonimizado a Uber', detected_language='en' WHERE post_id=2", u'Unroll.me CEO dice que es "desgarrador" que los usuarios se molesten Unroll.me vendi\xf3 sus datos de correo electr\xf3nico anonimizado a Uber')
使用 psycopg2
,当我使用:cur.execute(query)
我得到:
With psycopg2
, when I use: cur.execute(query)
I get:
TypeError: argument 1 must be a string or unicode object
使用查询和传递 unicode 值的最佳选择是什么.目前我已经参数化了 SQL 查询并传递了u".
What is the best option to use query and passing a unicode value. Currently Im already parametrizing the SQL query and passing the 'u'.
return u"UPDATE posts SET translated_text='%s', detected_language='%s' WHERE post_id=%s;" % (
translation, detected_language['language'], str(post_id))
我也添加了,没有任何区别:
I added also without making a difference:
import psycopg2.extensions
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
推荐答案
该日志显示了一个 元组 unicode 字符串,而不是一个 unicode 字符串.在执行检查之前尝试记录 query
的类型.
That log is showing a tuple of unicode strings, rather than a unicode string. Try logging the type of query
before you execute it to check.
记录参数化查询的首选方式是:
The preferred way to log parameterised query is:
query = u"UPDATE posts SET translated_text='%s', detected_language='%s' WHERE post_id=%s;"
vars = translation, detected_language['language'], str(post_id) # tuple
cur.execute(query, vars)
您可能还希望将 vars
的字符串显式转换为 unicode,而不是依赖于隐式完成.例如.
You may also wish to explicitly convert the strings of vars
into unicode rather than relying on this to be done implicitly. eg.
vars = translation, detected_language['language'].decode("utf8"), str(post_id).decode("utf8")
这篇关于类型错误:参数 1 必须是字符串或 unicode 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!