473,799 Members | 2,822 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

bartonc
6,596 Recognized Expert Expert
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.  
Mar 8 '07 #1
0 5243

Sign in to post your reply or Sign up for a free account.

Similar topics

1
1655
by: flupke | last post by:
I'm using wxPython and design the gui via wxglade. One of the gui components is a simple dialog class that gets displayed when a user exits the program. I want to use the same dialog but with a different text for closing certain dialogs in the program. (it's a pure "do you want to exit <insert screen name>" dialog) What would i better use, knowing the rest of the gui is in a resource (xrc) file:
2
1443
by: remedy | last post by:
how to create a model(Dialog) web page
4
5847
by: SteveK | last post by:
Hi- I have created a basic login form. If the user enters invalid credentials, I want to display an error. However, when the user presses the Login button, the dialog closes... I'm sure this is normal, but how can I interupt this and keep the dialog alive until I am ready for it to close? Thanks, Steve
0
1454
by: Ian | last post by:
I have sub-classed the Page class in order to provide some base properties and methods that every page on my site will need access to. I would like to have these things show up in the Simple Binding window of the DataBindings dialog. I then found this site (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vsintro7/html/vxurfDataBindingsDialogBox.asp) which says: The tree view displays these objects: the Page object; any...
14
3776
by: Simon Abolnar | last post by:
I would like to know how to open child form from dialog form. Thanks for help! Simon
18
13551
by: Dusty Hackney | last post by:
Hello, I am programming in Visual Basic .NET. I have seen examples of creating a login form to use for users to type in their username and password, but I want to accomplish the same thing with a pop-up dialog box instead. How can I make my program bring up a pop-up login dialog box for a user to type in username and password? Thanks, Dusty
0
5666
bartonc
by: bartonc | last post by:
#Boa:Dialog:DBConnectDialog import wx import wxdbtools as db def create(parent): return DBConnectDialog(parent) =
0
7701
bartonc
by: bartonc | last post by:
#Boa:Dialog:DBConnectDialog import wx ##"""Given a set if login specs, create a dbServer instance and ## ensure that there is a valid, open connection to the database. ## If not, set the dbConnect to None. ## spec: dict(UserName=name, Password=pswd, ServerName=host) ## Allow names to be set with Default Holder. Consiter Dictionary ## or even a tuple? (name, pswd, host)"""
14
1844
by: sumsin | last post by:
From 'Inside the C++ Object Model' by 'Stanley B. Lippman' 'The primary strength of the C++ Object Model is its space and runtime efficiency. Its primary drawback is the need to recompile unmodified code that makes use of an object of a class for which there has been an addition, removal, or modification of the nonstatic class data members.' Here I can understand the strength of C++ object model but can anybody elaborate the primary...
0
9689
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9550
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10495
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10032
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7573
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6811
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5469
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5597
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.