Skip to content

Instantly share code, notes, and snippets.

@folksilva
Created November 25, 2013 21:31
Show Gist options
  • Save folksilva/7649250 to your computer and use it in GitHub Desktop.
Save folksilva/7649250 to your computer and use it in GitHub Desktop.
Testes com PyODBC e MS Access
# -*- coding:utf-8 -*-
__author__ = 'Luiz Fernando da Silva <[email protected]>'
"""
Para consultar depois:
- Pynq: Expression Trees para Python, parecido com o Linq da Microsoft
"""
import pyodbc
dbpath = "c:\\Users\\LuizFernando\\Documents\\TesteACC2003.mdb"
driver = "{Microsoft Access Driver (*.mdb, *.accdb)}"
conn = pyodbc.connect("DRIVER={};DBQ={}".format(driver, dbpath))
cursor = conn.cursor()
class Table:
"""Mapeia uma tabela do banco para um objeto"""
def __init__(self, tablename, connection):
self.tablename = tablename
self.connection = connection
def get(self, id):
cursor = self.connection.cursor()
cursor.execute("SELECT * FROM %s WHERE id = ?" % self.tablename, id)
row = cursor.fetchone()
for t in row.cursor_description:
setattr(self, t[0], getattr(row, t[0]))
class Result:
"""Mapeia o resultado de uma consulta SELECT para um objeto"""
def __init__(self, row):
for t in row.cursor_description:
setattr(self,t[0], getattr(row, t[0]))
# Mapeando a tabela Teste e carregando o objeto com id 1
teste1 = Table('Teste', conn)
teste1.get(1)
print "Nome:", teste1.nome
# Uma consulta que mescla mais de uma tabela
cursor.execute("SELECT * FROM Teste INNER JOIN Teste2 ON Teste.id = Teste2.teste")
rows = cursor.fetchall()
objects = []
for row in rows:
objects.append(Result(row))
for obj in objects:
print obj.texto
@folksilva
Copy link
Author

Para ficar mais interessante, a classe Table precisa receber alguns métodos a mais. Ex.: query, join, save, delete etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment