hidura
hidura

Reputation: 693

How to conserve the integrity of the string from a database response using Python

i am using py-postgresql as the driver the database, when make a select to a string with non-ASCII characters, the response replace the character with "�" what can i make to change this to the correct character?

This is my code:

class decodify:

    def __init__(self):
        db = pgDriver.connect(user = 'demo', password='demo' database='hidura_karinapp', host='localhost', port='5432')
        d = db.prepare("""SELECT modules_reg.code FROM modules_reg, domain_reg, sbdomain_reg, sbdomdl_asc where(modules_reg.id = sbdomdl_asc.module AND modules_reg.mdname = 'police' AND sbdomain_reg.id = sbdomdl_asc.domain AND sbdomain_reg.domain = domain_reg.id AND domain_reg.dname = 'bmsuite.com' AND sbdomain_reg.sbname = 'www')""")
        s = d()
        print(s)

if __name__ == '__main__':
    decodify()

Upvotes: 1

Views: 240

Answers (4)

bobflux
bobflux

Reputation: 11581

You could use psycopg2, which supports unicode...

Upvotes: 0

Lennart Regebro
Lennart Regebro

Reputation: 172309

Are you setting a client_encoding ? In theory py-postgresql should use the correct client_encoding automatically. Either you are setting it to something wrong, or there is something wrong on how it detects it, in which case you have to set it. The question is then to what. :)

Upvotes: 1

Keith
Keith

Reputation: 43034

What I do is a trick to set the Python default encoding to the same as the database encoding. My database is UTF-8, so I have to start top-level scripts like this:

#!/usr/bin/python -S

import sys
sys.setdefaultencoding("utf-8")
import site

The all the strings come across clean, without translation. That's with Python 2.x. Python 3 may be different.

Upvotes: 0

Dave Shepard
Dave Shepard

Reputation: 527

What character encoding are you using in the database? Check the client_encoding setting in your postgresql.conf file, and see if that's utf-8 as well.

Upvotes: 0

Related Questions