Connecting Microsoft Access Database (DAO)

Thomas Keil t.keil at zvs.zgs.de
Fri Feb 18 01:45:41 CET 2000


Hello,

thanks for help! I finally used a query - perhaps its useful for someone
else:


# Getting a query from Access Database using DAO and SQL:


import win32com.client

FileName=r'example.mdb'

sql='SELECT * FROM [foo table];'  # "sql=foo table" does the same

# examples
#       Date='#02/05/00#'
#       sql='SELECT * FROM [foo table] WHERE [foobar] = %s' %Date

# joining 2 tables:
#       Tab1='[foo table]'
#       Tab2='[bar table]'
#       whereDef='WHERE [foobar] = %s' %Date

# ... with range:
#       whereDef='WHERE [foobar] BETWEEN %s AND %s' %(Date1, Date2)  
#       sql='SELECT * FROM '+Tab1+' INNER JOIN '+Tab2+' ON '+Tab1+'.ID =
'+Tab2+'.ID '+whereDef+';'


Engine='DAO.DBEngine.36'  

def Query(FileName, sql):             # have a look at the COM-tutorial
from Christian Tismer
  e=win32com.client.Dispatch(Engine)
  db=e.OpenDatabase(FileName)
  rs=db.OpenRecordset(sql)
  query=[]
  f=rs.Fields

  query.append(map(lambda fld: fld.Name, f))  # names

  rs.MoveFirst()                              # getting data
  while not rs.EOF:
    query.append(map(lambda fld: fld.Value, f))
    rs.MoveNext()   # ! never forget this
  db.Close()
  return (query)



for z in Query(FileName, sql): print z

#---

Th. Keil    mailto: t.keil at zvs.zgs.de



More information about the Python-list mailing list