0

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()
1
  • In sqlite3 you need to use ? or :name for parameter replacement... Use values (?, ?, NULL) instead... Commented Sep 8, 2013 at 14:10

1 Answer 1

2

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)))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.