简体   繁体   English

编写简单的查询,获取unicodeEncodeError,python 2.7

[英]Writing a simple query, getting a unicodeEncodeError, python 2.7

The query: 查询:

query = "SELECT * from "+str(tablename)+" where user='"+str(user)+"' AND review_title='"+rt+"'"

The error message: 错误信息:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128)

The code: 编码:

rt = review_title.replace("'", "\\'")
rt = rt.replace('"', '\\"')
rt = unicode(rt).encode('utf-8')
query = "SELECT * from "+str(tablename)+" where user='"+str(user)+"' AND review_title='"+rt+"'"

In this case the tablename is 'ta_rest_review' , the user is 'KANNONEPL...' and rt is 'Excelente pero \\"OJO a la CUENTA\\"' 在这种情况下,表名是'ta_rest_review'user'KANNONEPL...'rt'Excelente pero \\"OJO a la CUENTA\\"'

You should not use string formatting to interpolate your data. 应该使用字符串格式化插值数据。 Use SQL parameters instead! 请改用SQL参数!

Use the appropriate query parameter syntax for your database driver, it'll either use question marks or %s placeholders: 为数据库驱动程序使用适当的查询参数语法,它将使用问号或%s占位符:

cursor.execute(
    'SELECT * from {0} WHERE user=%s AND review_title=%s'.format(tablename),
    (user, rt)
)

You'll still have to interpolate the tablename (make absolutely sure it is an existing table name, don't take user input to determine this!) 您仍然必须插值表名( 绝对确保它是现有的表名,不要用用户输入来确定它!)

The database driver can then take care of escaping the user and rt values correctly for you, including encoding Unicode values to an encoding supported by the database. 然后,数据库驱动程序可以为您正确地转义userrt值,包括将Unicode值编码为数据库支持的编码。

Moreover, you avoid running the risk of a SQL injection security flaw if you try to 'escape' your database input yourself. 此外,如果尝试自己“转义”数据库输入,则可以避免出现SQL注入安全漏洞的风险。

Look at your database driver documenation; 查看您的数据库驱动程序文档。 the module should have a paramstyle variable that defines what style of parameter placeholder the driver supports, as well as explain if multiple styles are supported. 该模块应该有一个paramstyle变量 ,该变量定义驱动程序支持哪种样式的参数占位符,并说明是否支持多种样式。

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

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