Reputation: 1129
I have a textfield for user-input that adds data to a sqlite3 database with a Python-script. But my script breaks once the user enters a text with utf-8 characters:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 24: ordinal not in range(128)
Since the db string-entries are all unicode I suspect that my INSERT statement might cause the problem, but how can I pass utf-8-characters from the text input into the sqlite3 db, without converting them to %s strings? This is how I add the messages from the textarea:
c.execute("INSERT INTO messages VALUES ('%s', '%s', NULL)" % (threadinput , strip_html(newmessage)))
This is where I print the messages from the db, raising the 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()
Upvotes: 0
Views: 774
Reputation: 799420
This is how I add the messages from the textarea:
c.execute("INSERT INTO messages VALUES ('%s', '%s', NULL)" % (threadinput , strip_html(newmessage)))
Well there's your problem! </adam_savage>
c.execute("INSERT INTO messages VALUES (?, ?, NULL)", (threadinput , strip_html(newmessage)))
Upvotes: 2