photo
Jordan Sissel
geek

Sun, 23 Oct 2005

python, unicode, and pysqlite2

I have filenames I'm putting into an sqlite database. These filenames are ASCII encoded and may have upper-range characters in them. The problem, in python, is that the default encoding is UTF-8 and these ASCII upper-range characters, for whatever reason, cannot be converted. pysqlite2 provides a mechanism for fixing this problem with adapters and converters.

If you get this error:

UnicodeDecodeError: 'utf8' codec can't decode bytes in position [whatever]
Here's how I fix it (this may not be the proper solution):
from pysqlite2 import dbapi2 as sqlite

# ... several lines of code later ...

def decode_string(val):
	return val

def adapt_string(val):
	return unicode(val).encode("US-ASCII")

# ... somewhere ...

sqlite.register_adapter(str, adapt_string)
sqlite.register_converter('VARCHAR', decode_string)
I'm not certain the converter/decode is necessary, however the encoding is absolutely necessary.

Comments: 0 (view comments)
Tags: ,
Permalink: /geekery/192
posted at: 02:40


0 responses to 'python, unicode, and pysqlite2'


Leave a reply

You need javascript enabled to use this form. Anti-spam efforts ongoing. Also, if the comment doesn't show up, it's because the form expired. Go back and copy your comment, reload the form, and resubmit. Apologies if this is a hassle, I'm just playing with antispam methods right now. If this insists on not working, please email me about it.

Name (required)
E-mail (optional, if you want me to be able to email you back)
URL (also optional)
Comment:


Search this site

Navigation

Metadata

Home About Resume My Code (SVN)

Articles

ARP Security Dynamic DNS with DHCP OpenLDAP+Kerberos+SASL PPP over SSH SSH Security: /bin/false Week of Unix Tools Work Efficiency

Projects

fex firefox tabsearch firefox urledit grok keynav liboverride newpsm (FreeBSD) nis2ldap pam_captcha poor man's backup Solaris audio utility xboxproxy xdotool xmlpresenter xpathtool misc scripts

Presentations

Yahoo! Hack Day '08 Yahoo! Hack Day '06 Unix Essentials Vi/Vim Essentials SSH Tunneling (Video)

Tag Cloud

Calendar

< October 2005 >
SuMoTuWeThFrSa
       1
2 3 4 5 6 7 8
9101112131415
16171819202122
23242526272829
3031     

Friends

BarCamp Kent Brewster Tantek Çelik John Resig Wesley Shields Tyler Shields

Technorati