Inserting the utf-8 string in psycopg2 in python3 causes garbled characters

Asked 1 years ago, Updated 1 years ago, 80 views

If you insert a Japanese string of utf-8 into a column with type text in psycopg2 on python3, it becomes garbled.
What should I do?

The database encoding is UTF8

If you insert from psql, there will be no garbled characters, but if you insert with psycopg2 as shown below, it will be garbled


cursor.execute("insert into test_table(utf8_text)value(%(utf8_text)s);", 
{"utf8_text":"Hello"})


There seems to be an issue below, but how can I avoid this problem?
https://github.com/psycopg/psycopg2/issues/331

By the way, Python 3.5.2, Postgresql: 9.5.3, psycopg2: 2.6.2

python postgresql

2022-09-30 21:17

1 Answers

If you put u before the Japanese text, you might be able to avoid it.

cursor.execute("insert into test_table(utf8_text)value(%(utf8_text)s);", 
{"utf8_text":u "Hello"})


2022-09-30 21:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.