Created
January 16, 2012 00:33
-
-
Save danriti/1618221 to your computer and use it in GitHub Desktop.
Python + MySQLdb + Unicode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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