473,804 Members | 3,686 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

handling unicode data

Hi all,

I'm starting to learn python but am having some difficulties with how
it handles the encoding of data I'm reading from a database. I'm using
pymssql to access data stored in a SqlServer database, and the
following is the script I'm using for testing purposes.

-----------------------------------------------------------------------------
import pymssql

mssqlConnection =
pymssql.connect (host='localhos t',user='sa',pa ssword='passwor d',database='Te stDB')
cur = mssqlConnection .cursor()
query="Select ID, Term from TestTable where ID > 200 and ID < 300;"
cur.execute(que ry)
row = cur.fetchone()
results = []
while row is not None:
term = row[1]
print type(row[1])
print term
results.append( term)
row = cur.fetchone()
cur.close()
mssqlConnection .close()
print results
-----------------------------------------------------------------------------

In the console output, for a record where I expected to see "França"
I'm getting the following:

"<type 'str'>" - When I print the type (print type(row[1]))
"Fran+a" - When I print the "term" variable (print term)
"Fran\xd8a" - When I print all the query results (print results)
The values in "Term" column in "TestTable" are stored as unicode (the
column's datatype is nvarchar), yet, the python data type of the values
I'm reading is not unicode.
It all seems to be an encoding issue, but I can't see what I'm doing
wrong..
Any thoughts?

thanks in advance,
Filipe

Jun 28 '06 #1
22 6091
Filipe wrote:
In the console output, for a record where I expected to see "França"
I'm getting the following:

"<type 'str'>" - When I print the type (print type(row[1]))
"Fran+a" - When I print the "term" variable (print term)
"Fran\xd8a" - When I print all the query results (print results)

The values in "Term" column in "TestTable" are stored as unicode (the
column's datatype is nvarchar), yet, the python data type of the values
I'm reading is not unicode.
It all seems to be an encoding issue, but I can't see what I'm doing
wrong..


looks like the DB-API driver returns 8-bit ISO-8859-1 strings instead of Unicode
strings. there might be some configuration option for this; see

in worst case, you could do something like

def unicodify(value ):
if isinstance(valu e, str):
value = unicode(value, "iso-8859-1")
return value

term = unicodify(row[1])

but it's definitely better if you can get the DB-API driver to do the right thing.

</F>

Jun 28 '06 #2
Fredrik Lundh wrote:
looks like the DB-API driver returns 8-bit ISO-8859-1 strings instead of Unicode
strings. there might be some configuration option for this; see

Where did you want to point the OP here?
in worst case, you could do something like

def unicodify(value ):
if isinstance(valu e, str):
value = unicode(value, "iso-8859-1")
return value

term = unicodify(row[1])

but it's definitely better if you can get the DB-API driver to do the right thing.


It seems pymssql does not support such a thing.

Also, it appears that DB-Library (the API used by pymssql) always
returns CP_ACP characters (unless ANSI-to-OEM conversion is enabled);
so the "right" encoding to use is "mbcs".

Notice that Microsoft plans to abandon DB-Library, so it might be
best to switch to a different module for SQL Server access.

Regards,
Martin
Jun 28 '06 #3
Hi Fredrik,

Thanks for the reply.
Instead of:
term = row[1]
I tried:
term = unicode(row[1], "iso-8859-1")

but the following error was returned when printing "term":
Traceback (most recent call last):
File "test.py", line 11, in ?
print term
File "c:\Program Files\Python24\ lib\encodings\c p437.py", line 18, in
encode
return codecs.charmap_ encode(input,er rors,encoding_m ap)
UnicodeEncodeEr ror: 'charmap' codec can't encode character u'\xd8' in
position 31: character maps to <undefined>

Is it possible some unicode strings are not printable to the console?
It's odd, because I can manually write in the console the same string
I'm trying to print.
I also tried other encodings, besides iso-8859-1, but got the same
error.

Do you think this has something to do with the DB-API driver? I don't
even know where to start if I have to change something in there :|

Cheers,
Filipe

Jun 28 '06 #4
Filipe wrote:
Thanks for the reply.
Instead of:
term = row[1]
I tried:
term = unicode(row[1], "iso-8859-1")

but the following error was returned when printing "term":
Traceback (most recent call last):
File "test.py", line 11, in ?
print term
File "c:\Program Files\Python24\ lib\encodings\c p437.py", line 18, in
encode
return codecs.charmap_ encode(input,er rors,encoding_m ap)
UnicodeEncodeEr ror: 'charmap' codec can't encode character u'\xd8' in
position 31: character maps to <undefined>


works for me, given your example:
s = "Fran\xd8a"
unicode(s, "iso-8859-1")

u'Fran\xd8a'

what does

print repr(row[1])

print in this case ?

</F>

Jun 28 '06 #5
Hi,

Martin v. Löwis wrote:
Also, it appears that DB-Library (the API used by pymssql) always
returns CP_ACP characters (unless ANSI-to-OEM conversion is enabled);
so the "right" encoding to use is "mbcs".
do you mean using something like the following line?
term = unicode(row[1], "mbcs")

What do you mean by "ANSI-to-OEM conversion is enabled"? (sorry, I'm
quite a newbie to python)
Notice that Microsoft plans to abandon DB-Library, so it might be
best to switch to a different module for SQL Server access.


I've done some searching and settled for pymssql, but it's not too late
to change yet.
I've found these options to connect to a MSSqlServer database:

Pymssql
http://pymssql.sourceforge.net/

ADODB for Python (windows only)
http://phplens.com/lens/adodb/adodb-py-docs.htm

SQLServer for Python (discontinued?)
http://www.object-craft.com.au/projects/mssql/

mxODBC (commercial license)
http://www.egenix.com/files/python/mxODBC.html

ASPN Recipe
http://aspn.activestate.com/ASPN/Coo.../Recipe/144183
Pymssql seemed like the best choice. The ASPN Recipe I mention doesn't
look bad either, but there doesn't seem to be as many people using it
as using pymssql. I'll look a little further though.

Jun 28 '06 #6
Fredrik Lundh wrote:
works for me, given your example:
>>> s = "Fran\xd8a"
>>> unicode(s, "iso-8859-1")

u'Fran\xd8a'

what does
print repr(row[1])

print in this case ?


It prints:
'Fran\xd8a'

The error I'm getting is beeing thrown when I print the value to the
console. If I just convert it to unicode all seems ok (except for not
beeing able to show it in the console, that is... :).

For example, when I try this:
print unicode("Fran\x d8a", "iso-8859-1")

I get the error:
Traceback (most recent call last):
File "a.py", line 1, in ?
print unicode("Fran\x d8a", "iso-8859-1")
File "c:\Program Files\Python24\ lib\encodings\c p437.py", line 18, in
encode
return codecs.charmap_ encode(input,er rors,encoding_m ap)
UnicodeEncodeEr ror: 'charmap' codec can't encode character u'\xd8' in
position 4
: character maps to <undefined>

Jun 28 '06 #7
In <11************ **********@b68g 2000cwa.googleg roups.com>, Filipe wrote:
The error I'm getting is beeing thrown when I print the value to the
console. If I just convert it to unicode all seems ok (except for not
beeing able to show it in the console, that is... :).

For example, when I try this:
print unicode("Fran\x d8a", "iso-8859-1")

I get the error:
Traceback (most recent call last):
File "a.py", line 1, in ?
print unicode("Fran\x d8a", "iso-8859-1")
File "c:\Program Files\Python24\ lib\encodings\c p437.py", line 18, in
encode
return codecs.charmap_ encode(input,er rors,encoding_m ap)
UnicodeEncodeEr ror: 'charmap' codec can't encode character u'\xd8' in
position 4
: character maps to <undefined>


The `unicode()` call doesn't fail here but the ``print`` because printing
unicode strings means they have to be encoded into a byte string again.
And whatever encoding the target of the print (your console) uses, it
does not contain the unicode character u'\xd8'. From the traceback it
seems your terminal uses `cp437` as encoding.

As you can see here: http://www.wordiq.com/definition/CP437 there's no Ø
in that character set.

Ciao,
Marc 'BlackJack' Rintsch
Jun 28 '06 #8

Filipe wrote:
Hi,

I've done some searching and settled for pymssql, but it's not too late
to change yet.
I've found these options to connect to a MSSqlServer database:

Pymssql
http://pymssql.sourceforge.net/

ADODB for Python (windows only)
http://phplens.com/lens/adodb/adodb-py-docs.htm

SQLServer for Python (discontinued?)
http://www.object-craft.com.au/projects/mssql/

mxODBC (commercial license)
http://www.egenix.com/files/python/mxODBC.html

ASPN Recipe
http://aspn.activestate.com/ASPN/Coo.../Recipe/144183


You did not mention the odbc module from Mark Hammond's win32
extensions. This is what I use, and it works for me. I believe it is
not 100% DB-API 2.0 compliant, but I have not had any problems.

I have not tried connecting to the database from a Linux box (or from
another Windows box, for that matter). I don't know if there are any
implications there.

Frank Millman

Jun 29 '06 #9
Filipe wrote:
Also, it appears that DB-Library (the API used by pymssql) always
returns CP_ACP characters (unless ANSI-to-OEM conversion is enabled);
so the "right" encoding to use is "mbcs".
do you mean using something like the following line?
term = unicode(row[1], "mbcs")


Correct.
What do you mean by "ANSI-to-OEM conversion is enabled"? (sorry, I'm
quite a newbie to python)


It's an SQL server thing more than a Python thing. See AutoAnsiToOem
in

http://support.microsoft.com/default...B;EN-US;199819

Regards,
Martin
Jun 29 '06 #10

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

Similar topics

8
5280
by: Bill Eldridge | last post by:
I'm trying to grab a document off the Web and toss it into a MySQL database, but I keep running into the various encoding problems with Unicode (that aren't a problem for me with GB2312, BIG 5, etc.) What I'd like is something as simple as: CREATE TABLE junk (junklet VARCHAR(2500) CHARACTER SET UTF8)); import MySQLdb, re,urllib
4
6073
by: webdev | last post by:
lo all, some of the questions i'll ask below have most certainly been discussed already, i just hope someone's kind enough to answer them again to help me out.. so i started a python 2.3 script that grabs some web pages from the web, regex parse the data and stores it localy to xml file for further use.. at first i had no problem using python minidom and everything concerning
2
2537
by: kuhni | last post by:
Hi everybody! After searching newsgroups for a couple of hours, I now try asking directly (running the risk of asking again the same question). My problem is to predict when the size of the database (1GB I expect) is over 1GB by calculating the maximal number of data sets (tuple) added: 1. Is the following calculation for estimating the mdb file size in Access 97 correct: 1 integer field = 4 Byte
0
1169
by: Lau Lei Cheong | last post by:
Hello, I'm writing a project that involves entering chinese character into MySQL database. Since 1) connection-based coding selection requires an upgrade to version 4.1.1 or above and my company don't want to do that, 2) the web program will run in both big5 and gb2312 so I can't simply set the coding to big5, and 3) my company's backend is written in VB6.0 which is they told me do not support unicode(so I can't change the database's...
6
6618
by: John Sidney-Woollett | last post by:
Hi I need to store accented characters in a postgres (7.4) database, and access the data (mostly) using the postgres JDBC driver (from a web app). Does anyone know if: 1) Is there a performance loss using (multibyte) UNICODE vs (single byte) SQL_ASCII/LATINxxx character encoding? (In terms of extra data, and searching/sorting speeds).
1
4858
by: jrs_14618 | last post by:
Hello All, This post is essentially a reply a previous post/thread here on this mailing.database.myodbc group titled: MySQL 4.0, FULL-TEXT Indexing and Search Arabic Data, Unicode I was wondering if anybody has experienced the same issues
8
2360
by: Richard Schulman | last post by:
The following program fragment works correctly with an ascii input file. But the file I actually want to process is Unicode (utf-16 encoding). The file must be Unicode rather than ASCII or Latin-1 because it contains mixed Chinese and English characters. When I run the program below I get an attribute_count of zero, which is incorrect for the input file, which should give a value of fifteen or sixteen. In other words, the count...
44
9501
by: Kulgan | last post by:
Hi I am struggling to find definitive information on how IE 5.5, 6 and 7 handle character input (I am happy with the display of text). I have two main questions: 1. Does IE automaticall convert text input in HTML forms from the
17
4535
by: Adam Olsen | last post by:
As was seen in another thread, there's a great deal of confusion with regard to surrogates. Most programmers assume Python's unicode type exposes only complete characters. Even CPython's own functions do this on occasion. This leads to different behaviour across platforms and makes it unnecessarily difficult to properly support all languages. To solve this I propose Python's unicode type using UTF-16 should have gaps in its index,...
0
9706
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10335
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9157
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7621
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6854
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4301
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3821
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2993
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.