Inserting Unicode text with MySQLdb in Python 2.4-2.5?

Keith Hughitt keith.hughitt at gmail.com
Tue Nov 24 16:04:18 EST 2009


Hi John,

Thanks for the suggestions: I have finally been able to get it
working :)

In anyone else runs into the same problem, here is some example code
that works in Python 2.4+:

============= Begin Example ==================

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
def main():
    import MySQLdb, getpass

    admin = raw_input("Database admin: ")
    pw = getpass.getpass("Password: ")
    db = MySQLdb.connect(use_unicode=True, charset = "utf8",
user=admin, passwd=pw)

    cursor = db.cursor()
    try:
        cursor.execute("DROP DATABASE IF EXISTS unicode_test;")
        cursor.execute("CREATE DATABASE unicode_test DEFAULT CHARACTER
SET utf8;")
    except:
        print ""

    cursor.execute('''
    CREATE TABLE `unicode_test`.`test` (
      `id`          SMALLINT unsigned NOT NULL AUTO_INCREMENT,
      `name`        VARCHAR(255) NOT NULL,
       PRIMARY KEY (`id`), INDEX (`id`)
    ) DEFAULT CHARSET=utf8;''')

    cursor.execute("INSERT INTO `unicode_test`.`test` VALUES (NULL,
'%s');" % u"Ångström")

    # Test 1
    print "Just printing: %s" % 'Ångström'

    # Test 2
    cursor.execute("SELECT name FROM unicode_test.test;")
    print "From database: %s" % cursor.fetchone()[0]

    # Test 3 (Manual)
    print 'To verify manually: mysql -u %s -p -e "SELECT name FROM
unicode_test.test"' % admin

if __name__ == '__main__':
    sys.exit(main())

============= End Example ====================

Thanks all for taking the time to help!

Best,
Keith



More information about the Python-list mailing list