需要转换来自数据库的解码字符串

时间:2016-09-19 06:13:40

标签: python-2.7 utf-8 cgi decode

美好的一天,

我有一个问题,下面的代码,给我以下结果。

'HEllo there'] ['Unterl \ xc3 \ xa4nderstr。 46'] ['Weilimdorf B \ xc3 \ xbcrohaus'] ['物业名称'] ['你好在另一边'] ['Jahnstra \ xc3 \ x9fe'] ['Bahnhofstr。 15'] ['Karlsruher Str。 3'] ['Bahnhofstra \ xc3 \ x9fe 69'] ['Florians Haus'] ['物业编号22'] ['Schickardstr.36'] ['Clichystr。 6'] ['物业名称2'] ['Kirchstra \ xc3 \ x9fe 5']无

我需要将\ xc3 \ xa4显示为它们对应的UTF-8字母,但不能让它运行。我希望这里有人有类似的问题。

import cgi
import cgitb
cgitb.enable()
import sqlanydb

def db_dropdown():
  con = sqlanydb.connect( userid="DB", pwd="123", eng='DB',dbn='DB' )
  cursor = con.cursor()
  sql ="select distinct [Property] from Asset_Zielfonds"
  cursor.execute(sql)
  rowset = cursor.fetchall()
  encoded = [[s.encode('utf8') for s in t] for t in rowset]
  return encoded


def print_dropdown(data):  # Print the dropdown
    print '<div>'
    #print '<select>'
    for i in data:
        print '%s' % (i)
    #print '</select>'
    print '</div>'

print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<meta charset="ISO-8859-1">'
print '<head>'
print '</head>'
print '<body>'
print '<h2>Retrieval of Data from DB</h2>'
print '<br>'
print '<br>'
print '<br>'
print print_dropdown(db_dropdown())
print '<br>'
print '<br>'
print '<br>'
print '</body>'
print '</html>'

1 个答案:

答案 0 :(得分:0)

使用以下代码修复它。

def db_dropdown():  # Execute query
    db = sqlanydb.connect( userid="", pwd="", eng='',dbn='' )  # Your DB details here
    cursor = db.cursor()

    sql ="select distinct [Property] from assets where  [Property] is not NULL"

    cursor.execute(sql)
    list_tested = cursor.fetchall()  # Get query response and store in variable
    list_tested = [i for sub in list_tested for i in sub]  # Convert to list from tuple
    return list_tested



def print_dropdown(data):  # Print the dropdown
    print '<div>'
    print '<select>'
    for i in data:
      print '<option value="%s"selected>%s</option>' % (i.encode ('utf-8'), i.encode ('utf-8'))
    print '</select>'
    print '</div>'