testADOEvents.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from win32com.client import Dispatch, DispatchWithEvents, constants
  2. import pythoncom
  3. import os
  4. import time
  5. finished = 0 # Flag for the wait loop from (3) to test
  6. class ADOEvents: # event handler class
  7. def OnWillConnect(self, str, user, pw, opt, sts, cn):
  8. # Must have this event, as if it is not handled, ADO assumes the
  9. # operation is cancelled, and raises an error (Operation cancelled
  10. # by the user)
  11. pass
  12. def OnConnectComplete(self, error, status, connection):
  13. # Assume no errors, until we have the basic stuff
  14. # working. Now, "connection" should be an open
  15. # connection to my data source
  16. # Do the "something" from (2). For now, just
  17. # print the connection data source
  18. print("connection is", connection)
  19. print("Connected to", connection.Properties("Data Source"))
  20. # OK, our work is done. Let the main loop know
  21. global finished
  22. finished = 1
  23. def OnCommitTransComplete(self, pError, adStatus, pConnection):
  24. pass
  25. def OnInfoMessage(self, pError, adStatus, pConnection):
  26. pass
  27. def OnDisconnect(self, adStatus, pConnection):
  28. pass
  29. def OnBeginTransComplete(self, TransactionLevel, pError, adStatus, pConnection):
  30. pass
  31. def OnRollbackTransComplete(self, pError, adStatus, pConnection):
  32. pass
  33. def OnExecuteComplete(self, RecordsAffected, pError, adStatus, pCommand, pRecordset, pConnection):
  34. pass
  35. def OnWillExecute(self, Source, CursorType, LockType, Options, adStatus, pCommand, pRecordset, pConnection):
  36. pass
  37. def TestConnection(dbname):
  38. # Create the ADO connection object, and link the event
  39. # handlers into it
  40. c = DispatchWithEvents("ADODB.Connection", ADOEvents)
  41. # Initiate the asynchronous open
  42. dsn = "Driver={Microsoft Access Driver (*.mdb)};Dbq=%s" % dbname
  43. user = "system"
  44. pw = "manager"
  45. c.Open(dsn, user, pw, constants.adAsyncConnect)
  46. # Sit in a loop, until our event handler (above) sets the
  47. # "finished" flag or we time out.
  48. end_time = time.clock() + 10
  49. while time.clock() < end_time:
  50. # Pump messages so that COM gets a look in
  51. pythoncom.PumpWaitingMessages()
  52. if not finished:
  53. print("XXX - Failed to connect!")
  54. def Test():
  55. from . import testAccess
  56. try:
  57. testAccess.GenerateSupport()
  58. except pythoncom.com_error:
  59. print("*** Can not import the MSAccess type libraries - tests skipped")
  60. return
  61. dbname = testAccess.CreateTestAccessDatabase()
  62. try:
  63. TestConnection(dbname)
  64. finally:
  65. os.unlink(dbname)
  66. if __name__=='__main__':
  67. Test()