Skip to content

Instantly share code, notes, and snippets.

Created July 6, 2011 18:48
Show Gist options
  • Save ssbarnea/1068021 to your computer and use it in GitHub Desktop.
Save ssbarnea/1068021 to your computer and use it in GitHub Desktop.
Script to convert a a database to use utf8 encoding
#! /usr/bin/env python
import MySQLdb
host = "localhost"
passwd = ""
user = "root"
dbname = "mydbname"
db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=dbname)
cursor = db.cursor()
cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)
sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
results = cursor.fetchall()
for row in results:
sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
Copy link

ekine commented Feb 25, 2013

Hello Sorin,
when executing your conversion script I get this error:

Traceback (most recent call last):
File "", line 20, in
File "/usr/lib/pymodules/python2.7/MySQLdb/", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/pymodules/python2.7/MySQLdb/", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.IntegrityError: (1062, "Duplicate entry 'ich hasse meine mitsch\xc3\xbcler' for key 'idx_keyword_unq'")

At this point the script stops and all the remaining tables don't get converted. Also, where ever my content data has an umlaut (e.g. ö,ä,ü) a black diamond with a white question mark is being displayed.

Copy link

Thanks, it fixed my problem.

Copy link

great script thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment