我目前正在對我的postgresql數據庫運行一個查詢,忽略德語字符 - 元音變音。然而,我不想鬆散這些字符,並且寧願在查詢的輸出中使用德語字符或至少它們的等效字符(例如ä= ae)。運行Python的2.7.12如何使用ASCII字符查詢Unicode數據庫
當我改變編碼對象replace
或xmlcharrefreplace
我收到以下錯誤:
psycopg2.ProgrammingError: syntax error at or near "?"
LINE 1: ?SELECT
代碼段:
# -*- coding: utf-8 -*-
connection_str = r'postgresql://' + user + ':' + password + '@' + host + '/' + database
def query_db(conn, sql):
with conn.cursor() as curs:
curs.execute(sql)
rows = curs.fetchall()
print("fetched %s rows from db" % len(rows))
return rows
with psycopg2.connect(connection_str) as conn:
for filename in files:
# Read SQL
sql = u""
f = codecs.open(os.path.join(SQL_LOC, filename), "r", "utf-8")
for line in f:
sql += line.encode('ascii', 'replace').replace('\r\n', ' ')
rows = query_db(conn, f)
我如何傳遞一個查詢作爲帶德文字符的unicode對象? 我也嘗試解碼的查詢作爲utf-8
但後來我得到以下錯誤:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)
我對這個問題有點困惑,我認爲是因爲術語問題。當你說「ASCII字符」時,你是否確實是指「不適合ASCII的字符」? [ASCII](https://en.wikipedia.org/wiki/ASCII)是一種7位編碼,僅涵蓋英文使用的羅馬字母的部分(無重音符號或變音符號)。這聽起來像你在談論你想要的東西。 – Blckknght