Connecting Tech Pros Worldwide Help | Site Map

The Model used by wx.Dialog subclass for DB login.

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



Reply