Here is my code, which connects to database, and inserts russian word into database:
import mysql.connector
if __name__ == '__main__':
try:
cnx = mysql.connector.connect(user='user', password='password',
host='123.123.123.123',
database='db_name',
charset='utf8',
collation='utf8_general_ci',
use_unicode=True)
except BaseException as ex:
print('Error: ' + str(ex))
cnx.close()
else:
print('Connections succesful!')
cnx.set_charset_collation('utf8', 'utf8_general_ci')
cursor = cnx.cursor()
print(cnx.charset)
cursor.execute("INSERT INTO table_name (column_name) values ('привет!')") #means 'Hello!' in russian
cursor.execute("SELECT * FROM test_referers")
print(cursor.fetchall())
And here is what I get:
Connection succesful!
utf8
(1, u'\u043f\u0440\u0438\u0432\u0435\u0442!')
Such output appears in both Python interpreter console and Eclipse PyDev.
Kindly help
Your output is valid Unicode. Python echoes that back to you with Unicode escape values (
\uxxxx) because the row consists of a tuple with two items; when printing a tuple it’s contents are represented as python literals instead.If you were to use the following code:
instead it would print:
You can test this by printing the literal value with the python prompt: