473,388 Members | 1,493 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

Setting the encoding in pysqlite2

An easy question, but I don't find the answer in the docs :-(
I have a sqlite3 database containing accented characters (latin-1).
How do I set the right encoding? For instance if I do this:

#-*- encoding: latin-1 -*-
from pysqlite2 import dbapi2 as sqlite
import os

DBFILE="/tmp/example.db"

def writedb(conn):
c = conn.cursor()
c.executescript("""
create table example (word char(20));
insert into example values ("così");
""")
c.close()

def readdb(conn):
c = conn.cursor()
c.execute("select * from example;")
#print c.fetchall()
c.close()

if __name__ == "__main__":
conn = sqlite.connect(DBFILE)
writedb(conn)
readdb(conn)
conn.close()
os.remove(DBFILE)

I get UnicodeDecodeError: 'utf8' codec can't decode byte 0xec in
position 3: unexpected end of data
(notice, even if the 'print' statement is commented.
Michele Simionato

Aug 25 '05 #1
5 2277
Michele Simionato ha scritto:
An easy question, but I don't find the answer in the docs :-(
I have a sqlite3 database containing accented characters (latin-1).
How do I set the right encoding? For instance if I do this:


Hi,
i usually use this "string" method:

encode([encoding[,errors]])

An example:

cur.execute("""
insert into tab(
field1,
field2)
values (?,?)
""" , (myvar1.encode('utf8'),\
myvar2.encode('utf8')))

Bye,
Renzo
Aug 25 '05 #2
Well, the issue is not how to input text in the database from Python
(it is enough to use literal unicode strings);
in my case the database has been generated from a text file containing
accented chars, using .import,
and it seems I cannot read it from Python because of the unicode error
:-(

Michele Simionato

Aug 26 '05 #3
Michele Simionato wrote:
An easy question, but I don't find the answer in the docs :-(
I have a sqlite3 database containing accented characters (latin-1).
How do I set the right encoding? For instance if I do this:


I think you should ask on the pysqlite-devel list.

Reinhold
Aug 26 '05 #4
Michele Simionato wrote:
Well, the issue is not how to input text in the database from Python
(it is enough to use literal unicode strings);
in my case the database has been generated from a text file containing
accented chars, using .import,
and it seems I cannot read it from Python because of the unicode error
:-(


You should not do that. In SQLite 3, TEXT fields should always be
UTF-8. That .import did not reject your data sounds like a bug in
..import.

So if you make your input data UTF-8, you should be able to fetch
them easily, and receive Unicode strings.

Regards,
Martin
Aug 26 '05 #5
On Thu, Aug 25, 2005 at 01:15:55AM -0700, Michele Simionato wrote:
An easy question, but I don't find the answer in the docs :-(
I have a sqlite3 database containing accented characters (latin-1).
How do I set the right encoding? For instance if I do this: [...]


You cannot set the encoding directly, because TEXT data in SQLite3
databases is expected to be in UTF-8 encoding. If you store "weird"
TEXT, you can work around it by using a custom converter in pysqlite2,
like in the following example:

#-*- encoding: latin-1 -*-
from pysqlite2 import dbapi2 as sqlite

# Register an additional converter for plain bytestrings
sqlite.register_converter("bytestring", str)

con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(t)")

testdata = "Häring" # bytestring in ISO-8859-1 encoding

cur.execute("insert into test(t) values (?)", (testdata,))

# Try to retrieve the test data, will fail
try:
cur.execute("select t from test")
except UnicodeDecodeError:
print "Could not decode latin1 as utf-8 (as expected)"

# Via the PARSE_COLNAMES trick, explicitly choose the bytestring converter
# instead of the default unicode one:
cur.execute('select t as "t [bytestring]" from test')
result = cur.fetchone()[0]
assert testdata == result
print "Correctly retrieved test data"

HTH,

-- Gerhard
Aug 26 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: F. GEIGER | last post by:
Im on Python 2.3.4, using pysqlite 2.0.0 (final). When I try to execute self._dbc.execute(q, data) where q is 'select count(*) from Difflets ' and date is None I get the following...
1
by: F. GEIGER | last post by:
I've troubles to let my app take off using pysqlite. What I wonder most for now is that "pysqlite2.dbapi2.OperationalError: cannot commit transaction - SQL statements in progress" when I do this:...
1
by: qvx | last post by:
I really can't seem to make sqlobject/pysqlite2 save my local Easter European characters. I am a Windows-1250 user and I have sys.setdefaultencoding('dbcs') in my sitecustomize. How can I...
3
by: xmlguy | last post by:
XmlTextReader myXmlReader = new XmlTextReader(args); string en = myXmlReader.Encoding.EncodingName; //Console.WriteLine(x); Error: Unhandled Exception: System.NullReferenceException: Object...
16
by: Greg Miller | last post by:
I have an application that uses sqlite3 to store job/error data. When I log in as a German user the error codes generated are translated into German. The error code text is then stored in the db....
0
by: schwehr | last post by:
Hi All, I have some old pysqlite 1.x code that uses a pattern like this: cu.execute('SELECT weight FROM weights WHERE samplename="foo") row = cu.fetchone() weight=row It seems like lookups...
1
by: laredotornado | last post by:
Hi, I'm using PHP 4.4.4 on Apache 2 on Fedora Core 5. PHP was installed using Apache's apxs and the php library was installed to /usr/local/php. However, when I set my "error_reporting"...
0
by: Daniel | last post by:
how does ado.net SqlDataReader.GetString() know which encoding to read the data into a string as? Does sql sever set this at the column data type level, server wide encoding setting, os encoding?
1
by: Torsten Bronger | last post by:
Hallöchen! I start a python script with subprocess from another Python script with python = subprocess.Popen(, stdout=subprocess.PIPE, stderr=subprocess.PIPE) However, this child script...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.