数据库登录现在使用mxODBC

只需对视图/控件进行一个小小的更改:

选择 | 换行 | 行号
  1.         self.staticText3 = wx.StaticText(id=wxID_DBCONNECTDIALOGSTATICTEXT3,
  2.                 label='ODBC Data Source Name', name='staticText3', parent=self, pos=wx.Point(240,
  3.                 40), size=wx.Size(143, 16), style=0)

以及对模型的一些修改:

选择 | 换行 | 行号
  1. ##from MySQLdb import *
  2. from mx.ODBC.Windows import *
  3. from time import time
  4.  
  5. class DBServer:
  6.     def __init__(self, master):
  7.         self.master = master
  8.  
  9.     def Login(self, servername, username, password):    #, database=""
  10.         """Attempt to create a database login. If successful, return
  11.            an open connection. Otherwise, return None."""
  12.         try:
  13.             self.dbconnect = Connect(servername, user=username, password=password,
  14.                                      clear_auto_commit=0) #, host=servername
  15. ##            self.dbconnect = connect(host=servername, user=username, passwd=password)   #, db=database
  16.         except (DatabaseError, OperationalError):
  17.             self.dbconnect = None
  18.             self.dbcursor = None
  19.             self.master.write('Couldn\'t log on to the server `%s` as `%s`\n' %(servername, username))
  20.             return
  21.         self.master.write("%s has been logged onto %s\n" %(username, servername))
  22.         self.dbcursor = self.dbconnect.cursor()
  23.         self.Execute('SET autocommit=1')
  24.         return self.dbconnect
  25.  
  26.     def DBError(self, query, message):
  27.         """Remove the current message from the cursor
  28.            and display it. Report the query and error to the master."""
  29.         print message
  30. ##        try:
  31. ##            (error, message) = self.dbcursor.messages.pop()
  32. ##        except AttributeError:
  33. ##            (error, message) = self.dbconnect.messages.pop()
  34. ##        self.master.write('%s\n%s #%d:  %s\n' %(query, str(error).split('.')[-1],
  35. ##                                                message[0], message[1]))
  36.         self.master.write('%s\nOCDB Error %s #%d:  %s #%d\n' %(query, message[0], message[1],
  37.                           message[-2].split(']')[-1], message[-1]))
  38.  
  39.     def IsOpen(self, connection):
  40.         return not connection.closed
  41.  
  42.     def Execute(self, query):
  43.         """Execution method reports on the number of rows affected and duration
  44.            of the database query execution and catches errors. Return a reference
  45.            to the cursor if no error ocurred, otherwise, None."""
  46.         cursor = self.dbcursor
  47.         if cursor:
  48.             try:
  49.                 now = time()
  50.                 cursor.execute(query)
  51.                 nRows = cursor.rowcount
  52.                 self.master.write("%s   " % query)
  53.                 self.master.write("%d rows affected: %.2f sec.\n" %(nRows, time() - now))
  54.             except (DatabaseError, OperationalError), message:
  55.                 self.DBError(query, message)
  56.                 return
  57.             return cursor
  58.  
  59.     def DBExists(self, database):
  60.         """Return True if database exists"""
  61.         cursor = self.Execute("show databases")
  62.         if cursor:
  63.             rows = cursor.fetchall()
  64.             return (database.strip('`').lower(),) in rows
  65.  
  66.     def TableExists(self, table):
  67.         """Return True if database exists"""
  68.         cursor = self.Execute("show tables")
  69.         if cursor:
  70.             rows = cursor.fetchall()
  71.             return (table.strip('`').lower(),) in rows
  72.  
  73.     def SetMaster(self, master):
  74.         """Allow the master to be reset."""
  75.         self.master = master
  76.  
  77.     def GetMaster(self):
  78.         return self.master
  79.  
  80.     def GetDbConnection(self):
  81.         return self.dbconnect
  82.  
  83.     def close(self):
  84.         try:
  85.             self.dbconnect.close()
  86.             self.master.write("Closed connection.\n")
  87.         except ProgrammingError:
  88.             self.master.write("Already closed!\n")
  89.  
  90.  
  91. class DBClient:
  92.     """Subclass this class and override the write() method,
  93.        or provide these minimal services in your own class."""
  94.     def __init__(self, database):
  95.         ## Connect to the SQL data base
  96.         self.dbServer = DBServer(self, database)
  97.  
  98.     def write(self, message):
  99.         print message
  100.  
  101.  
  102.  
  103. ## Probably don't want to give default values to parameters in utility routines...
  104. ## Do some tests some day to look at side effects...
  105.  
  106. def MySQLDelete(table, argdict={}, **kwargs):
  107.     """Build an SQL DELETE command from the arguments:
  108.     Return a single string which can be 'execute'd.
  109.     argdict and kwargs are two way to evaluate 'colName':value
  110.     for the WHERE clause."""
  111.     args = argdict.copy()
  112.     args.update(kwargs)
  113.     for key, value in args.items():
  114.         args[key] = (str(value), repr(value))[type(value) == str]
  115.     b = ''
  116.     if args:
  117.         b = 'WHERE %s' % ' AND '.join(key + '=' + value
  118.                                       for key, value in args.items())
  119.     return ' '.join(['DELETE FROM', table, b])
  120.  
  121. def MySQLInsert(table, argdict={}, **kwargs):
  122.     """Build an SQL INSERT command from the arguments:
  123.     Return a single string which can be 'execute'd.
  124.     argdict is a dictionary of 'column_name':value items.
  125.     **kwargs is the same but passed in as column_name=value"""
  126.     args = argdict.copy()   # don't modify caller dictionary!
  127.     args.update(kwargs)
  128.     keys = args.keys()
  129.     argslist = []
  130.     for key in keys:
  131.         a = args[key]
  132.         argslist.append((str(a), repr(a))[type(a) == str])
  133.     # wrap comma separated values in parens
  134.     a = '(%s)' %', '.join(field for field in keys)
  135.     b = '(%s)' %', '.join(argslist)
  136.     return ' '.join(['INSERT', table, a, 'VALUES', b])
  137.  
  138.  
  139. def MySQLUpdate(table, valuedict, argdict={}, **kwargs):
  140.     """Build an SQL SELECT command from the arguments:
  141.     Return a single string which can be 'execute'd.
  142.     valuedict is a dictionary of column_names:value to update.
  143.     argdict and kwargs are two way to evaluate 'colName'=value
  144.     for the WHERE clause."""
  145.     vargs = valuedict.copy()
  146.     for key, value in vargs.items():
  147.         vargs[key] = (str(value), repr(value))[type(value) == str]
  148.     a = 'SET %s' % ', '.join(key + '=' + value
  149.                                   for key, value in vargs.items())
  150.     args = argdict.copy()
  151.     args.update(kwargs)
  152.     for key, value in args.items():
  153.         args[key] = (str(value), repr(value))[type(value) == str]
  154.     b = ''
  155.     if args:
  156.         b = 'WHERE %s' % ' AND '.join(key + '=' + value
  157.                                       for key, value in args.items())
  158.  
  159.     return ' '.join(['UPDATE', table, a, b])
  160.  
  161.  
  162. def MySQLSelect(table, arglist=[], argdict={}, **kwargs):
  163.     """Build an SQL SELECT command from the arguments:
  164.     Return a single string which can be 'execute'd.
  165.     arglist is a list of strings that are column names to get.
  166.     argdict and kwargs are two way to evaluate 'colName'=value
  167.     for the WHERE clause"""
  168.     a = ', '.join(arglist)
  169.     args = argdict.copy()
  170.     args.update(kwargs)
  171.     for key, value in args.items():
  172.         args[key] = (str(value), repr(value))[type(value) == str]
  173.     b = ''
  174.     if args:
  175.         b = 'WHERE %s' % ' AND '.join(key + '=' + value
  176.                                       for key, value in args.items())
  177.  
  178.     return ' '.join(['SELECT', (a or '*'), 'FROM', table, b])
  179.  
  180.  
  181. def Py2SQL_Join(tables, mapping, *arglist, **kwargs):
  182.     """Build an SQL SELECT command from the arguments:
  183.     Return a single string which can be 'execute'd.
  184.     tables is a list of strings that are table names to get from.
  185.     mapping is a list of tuples that maps table[:] to arglist[]
  186.     arglist is a list of strings that are column names to get.
  187.     argdict and kwargs are two way to evaluate 'colName'=value
  188.     for the WHERE clause. There may be a way to map this dict,
  189.     but for now, keys must be unique across tables."""
  190.  
  191.     a = ', '.join(['%s.%s' %(tables[mapping[i][0]], arglist[mapping[i][1]]) for i in range(len(mapping))])
  192.  
  193.     for key, value in kwargs.items():
  194.         kwargs[key] = (str(value), repr(value))[type(value) == str]
  195.     b = ', '.join(tables)
  196.  
  197.  
  198.     # this is just wrong! it randomly pops from dict, and using tables[1] doesn't make sense!
  199.     try:
  200.         k, v = kwargs.popitem()
  201.     except KeyError:
  202.         k = ''
  203.     if k:
  204.         kwargs.update({'%s.%s' %(tables[1], k):v})
  205. #    kwargs.update({'%s.%s' %(tables[0], priKeyName):'%s.%s' %(tables[1], priKeyName)})
  206.  
  207.  
  208.     c = ''
  209.     if kwargs:
  210.         c = 'WHERE %s' % ' AND '.join(key + '=' + value
  211.                                       for key, value in kwargs.items())
  212.  
  213.     return ' '.join(['SELECT', (a or '*'), 'FROM', b, c])
  214.  
  215. if __name__ == "__main__":
  216.     pass
  217. ##    import sys
  218. ##    db = DBServer(sys.stdout)
  219. ##
  220. ##    con = db.Login('genesis', 'joe', 'password')
  221. ##    print con
  222. ##    print db.IsOpen(con)

可以访问任何数据库。

标签: python

评论已关闭