Switched to MySQLdb; cleaned up code