#! /usr/bin/python
# -*- coding: iso-8859-1 -*-

#####################################################
#    Copyright (C) 2006 by Cesar Kallas   	
#    cesarkallas@soulivre.org   
#    http://cesarkallas.soulivre.org
#                                                                          
#    This program is free software; you can redistribute it and#or modify  
#    it under the terms of the GNU General Public License as published by 
#    the Free Software Foundation; either version 2 of the License, or     
#    (at your option) any later version.                                   
#                                                                          
#    This program is distributed in the hope that it will be useful,       
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         
#    GNU General Public License for more details.                          
#                                                                          
#    You should have received a copy of the GNU General Public License     
#    along with this program; if not, write to the                         
#    Free Software Foundation, Inc.,                                       
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             
#####################################################

import MySQLdb
import MySQLdb.cursors
import Log

class BancoDados( object ):
	"""
	Classe que gerencia a conexao com o banco de dados MySQL
	Data: 04/09/2006
	"""
	global cursor
	
	def __init__(self, host, usuario, senha, base):
		self.host = host
		self.usuario = usuario
		self.senha = senha
		self.base = base
		
		# Inicia Log do Banco De Dados
		self.log = Log.Log("BancoDados")
		self.log = self.log.get()
		

	def conectar(self):
		"""
		Funcao que conecta na base de dados MySQL
		Entradas: self.host, self.usuario, self.senha, self.base
		Retorno: self.cursor, 'None' para falha
		"""
		try:
			self.conn = MySQLdb.connect(host=self.host, user=self.usuario, passwd=self.senha, db=self.base, compress=1)
			self.conn.autocommit(1)
			self.cursor = self.conn.cursor()
			self.cursor = self.conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)	# O resultado sera no formato de dicionarios
			return self.cursor
		except MySQLdb.Error, e:
			self.log.warn("%d: %s" % (e.args[0], e.args[1]))
			return None
			
	def desconectar(self):
		self.cursor.close()
		self.conn.close()

