problem when entering Unicode value into database

Asked

Viewed 170 times

1

I am breaking my head with this since yesterday I have done everything to enter 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 happens the second error

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 this of the following format

my bank and scrit is all in UTF8

someone could help me get around this problem

  • Try to use the method decode see: string = "João e o Pé de Feijão".decode('utf8')

  • there is the u note at the beginning of my Unicode string I want to convert to utf8 to insert into my database

  • @drmcarvalho now returned me Unicodeencodeerror: 'ascii' codec can’t Encode Character u' xe3' in position 2: ordinal not in range(128)

  • I edited the question because "phpmyadmin" is not a "database", read this to understand the differences: What is the difference between mysql and phpmyadmin?

1 answer

2


Try to make the argument charset='utf8' when to connect. Type:

db = MySQLdb.connect("localhost", "devel", "********", "Ditados", charset='utf8')
  • 1

    vlw guy was that same vlw +1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.