2015-05-31 36 views
0

我使用cgi,python 2.7和sqlite。通過python 2.7,cgi和html添加Å,Ä和Ö到sqlite表格

我想插入一個字符串?包含字符å,ä和ö到sqlite表中。

print '<form action="./printusername.cgi" method="post">' 
print 'First Name: <input type="text" name="first_name">' 
print '</form>' 

1M在printusername.cgi接收這樣的值::

import cgi 
cgitb.enable() 
form = cgi.FieldStorage() 
first_name = form.getvalue('first_name') 

字符串從一個html交使用CGI

這個代碼在取值取然後我試圖將它傳遞到一個SQLite表,沿着白衣一些其他值,如下所示:

import sqlite3 
con = sqlite3.connect('Addressbook.db') 
cursor = con.cursor() 
contact = (first_name,other_valu_1,other_valu_1) 
cursor.execute("INSERT INTO entrys VALUES(?, ?, ?)",contact) 

當我這樣做,我會收到以下錯誤:

<class 'sqlite3.ProgrammingError'>: You must not use 8-bit bytestrings 
unless you use a text_factory that can interpret 8-bit bytestrings 
(like text_factory = str). It is highly recommended that you instead 
just switch your application to Unicode strings. 

,如果我不使用A,A或o在HTML後一切工作正常。

爲什麼會發生此錯誤?我怎樣才能避免它,並仍然保持sqlite表中的數據可讀?

如果數據需要格式化,下次何時可以訪問它時如何合成它?

所有幫助表示讚賞! sry 4我的壞英文。

回答

2

您的瀏覽器的文章編碼字符串到服務器。它使用的編碼取決於原始網頁的編碼方式,但通常意味着UTF-8。你需要解碼這些值到unicode使用該編碼的對象。

最好的辦法是告訴瀏覽器發送HTML表單時,通過將內容編碼到Content-Type頭使用何種編解碼器:

print 'Content-Type: text/html; charset=utf-8' 

,然後在接收數據時,嘗試解碼數據:

try: 
    first_name = form.getvalue('first_name').decode('utf8') 
except (AttributeError, UnicodeDecodeError): 
    # Could not decode or there was no such field 
    # Handle the error. 

您可能需要Python和Unicode的讀了起來:

+0

gr8th鏈接和一個明確的答案!謝謝你,問題解決了! +1 – user3416789

相關問題