Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy and python - retrieving non-ascii chars from DB

My question: Why can't I retrieve non-ascii chars from sqlalchemy db into python?

In more detail: I have an entry with non-ascii char in my sqlalchemy db (Umlaut for example). When I try to retrieve this entry by using:

q=self.session.query(Table_Name).filter(Table_Name.id=='some id')
q.all()

I receive the following error:

UnicodeEncodeError: 'ascii' codec can't encode characters in position

I solved it by decoding the entries into UTF-8 before inserting the entry to the DB.

Yet I wondered - why does this error appeared? Is there an option to fetch entries already encoded as unicode for example instead of bytechar\ascii into python?

like image 527
Maoritzio Avatar asked Jan 21 '26 21:01

Maoritzio


1 Answers

Per the docs, you should specify the encoding in the connection string:

e = create_engine("mysql+pymysql://scott:tiger@localhost/test?charset=utf8")
like image 196
Sam Avatar answered Jan 23 '26 11:01

Sam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!