【问题标题】:Write/Read utf-8 from sqlite3 db with Python web interface使用 Python Web 界面从 sqlite3 db 写入/读取 utf-8
【发布时间】:2013-09-08 22:10:55
【问题描述】:

我有一个用于用户输入的文本字段,它使用 Python 脚本将数据添加到 sqlite3 数据库。但是一旦用户输入带有 utf-8 字符的文本,我的脚本就会中断:

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

由于 db 字符串条目都是 unicode,我怀疑我的 INSERT 语句可能会导致问题,但是如何将文本输入中的 utf-8 字符传递到 sqlite3 db,而不将它们转换为 %s 字符串?这就是我从 textarea 添加消息的方式:

c.execute("INSERT INTO messages VALUES ('%s', '%s', NULL)" % (threadinput , strip_html(newmessage)))

这是我从数据库打印消息的地方,引发 UnicodeError:

conn = sqlite3.connect('msg.db')
c = conn.cursor()
c.execute("SELECT * FROM messages WHERE thread ='%s' ORDER BY nr ASC" % threadinput)
rows = c.fetchall()
count = 1
for row in rows:
        print "<li>Message Nr. %s: %s</li>" % (count, row)
        count += 1
conn.close()

【问题讨论】:

  • 在 sqlite3 中,您需要使用?:name 进行参数替换...改用values (?, ?, NULL)...

标签: python unicode utf-8 sqlite


【解决方案1】:

这是我从 textarea 添加消息的方式:

c.execute("INSERT INTO messages VALUES ('%s', '%s', NULL)" % (threadinput , strip_html(newmessage)))

你的问题!

c.execute("INSERT INTO messages VALUES (?, ?, NULL)", (threadinput , strip_html(newmessage)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    • 2010-10-04
    相关资源
    最近更新 更多