problem inserting unicode value into database

1

I'm breaking my head with this since yesterday I've done everything to insert the value in utf8 but it is not working and the following I have this code as an example

#!/usr/bin python
# -*- coding: utf-8 -*-

import MySQLdb

db = MySQLdb.connect("localhost", "devel", "********", "Ditados")
cursor = db.cursor()
# cursor.execute("SET NAMES utf8mb4;")
# cursor.execute("SET CHARACTER SET utf8mb4;")
# cursor.execute("SET character_set_connection=utf8mb4;")

autor = u"Desconhecido"
string = u"João e o Pé de Feijão"

sql = "INSERT INTO textos(autor, texto) VALUES ('%s', '%s')" % (autor, string)
cursor.execute(sql)
cursor.fetchone()
db.commit()
db.close()

When I run this script the following error occurs

Warning: Incorrect string value: '\xE3o e o...' for column 'texto' at row 1 cursor.execute(sql)

When I go to see in the database the text is of the following format

MybankandscritareallinUTF8

Can anyone help me get around this problem?

    
asked by anonymous 11.06.2016 / 22:31

1 answer

2

Try to put the charset='utf8' argument when connecting. Type:

db = MySQLdb.connect("localhost", "devel", "********", "Ditados", charset='utf8')
    
12.06.2016 / 00:38