Skip to content

Instantly share code, notes, and snippets.

@danriti
Created January 16, 2012 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danriti/1618221 to your computer and use it in GitHub Desktop.
Save danriti/1618221 to your computer and use it in GitHub Desktop.
Python + MySQLdb + Unicode
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb as mysql
def QueryDatabase(query, values):
"""Function to query a MySQL database and return the results of the
query."""
# Initialize variables and return values.
conn = None
rows = []
try:
# Create a connection to the database.
conn = mysql.connect(host='127.0.0.1',
user='user',
passwd='passwd',
db='db',
charset='utf8',
use_unicode=True)
cursor = conn.cusor()
# Execute the SQL query.
cursor.execute(query, values)
# Fetch all the rows from the query.
rows = cursor.fetchall()
# Clean up.
cursor.close()
conn.commit()
conn.close()
except:
# Attempt to close the connection if one still exists.
if conn:
conn.close()
return rows
def Main():
print "Unicode Test!"
# Example INSERT query on a fictional database.
QueryDatabase('INSERT INTO mytable VALUES (null, %s)',
('Some string that contains unicode: ' + unichr(300),))
if __name__ == "__main__":
Main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment