mysql cur.execute()读取unicode字符错误

时间:2015-08-05 18:20:35

标签: python jdbc unicode string-formatting teradata

我的代码:

#-*- coding: utf-8 -*-
connection = jaydebeapi.connect(#my connection params) #Path to JDBC Driver
cur = connection.cursor()
country='US'
mylist = ['你好','我是明']

这是我的查询字符串:

    myquery="""create table mytable as (
    select * from table1 where country='%s' 
    and terms like any ('%s');""" % (country, "', '".join(mylist))

    cur.execute(myquery)

当我这样做时: cur.execute(myquery) 我收到错误:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 301: ordinal not in range(128)

尽管print myquery 返回mylist中的字符串就好了。

如何在cur.execute()

中对查询字词进行编码

1 个答案:

答案 0 :(得分:0)

找到了我的答案 - 在字符串格式化过程中必须解码mylist中的每个字符串:

  myquery="""create table mytable as (
    select * from table1 where country='%s' 
    and terms like any ('%s');""" % (country, "', '".join([i.decode('utf-8') for i in mylist]))