473,396 Members | 2,129 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,396 developers and data experts.

Database Login now uses mxODBC

bartonc
6,596 Expert 4TB
With one small change to the view/control:
Expand|Select|Wrap|Line Numbers
  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)
and some rework of the model:
Expand|Select|Wrap|Line Numbers
  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)
Any DB can be accessed.
Mar 12 '07 #1
0 4972

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

Similar topics

13
by: SectorUnknown | last post by:
I've written a database (Access mdb) front-end using Python/wxpython/and ADO. However, the scope of the project has changed and I need to access the same data on an MSSQL server. Also, the...
23
by: ajikoe | last post by:
Hello I need to build table which need searching data which needs more power then dictionary or list in python, can anyone help me what kind of database suitable for python light and easy to learn....
5
by: kyosohma | last post by:
Hi, I am populating a mySQL database with data from the MS Access database. I have successfully figured out how to extract the data from Access, and I can insert the data successfully into mySQL...
4
by: coldpizza | last post by:
Hi, I want to run a database query and then display the first 10 records on a web page. Then I want to be able to click the 'Next' link on the page to show the next 10 records, and so on. My...
5
by: MindMaster32 | last post by:
I am writing a script that has to read data from an ASCII file of about 50 Mb and do a lot of searches and calculations with that data. That would be a classic problem solved by the use of a...
10
by: giraffeboy | last post by:
Hi there, I'm having a problem with the Python db api, using MySQL. I've written a program with a GUI using wxPython, the GUI is contained in main.py which imports another module - reports.py....
0
by: M.-A. Lemburg | last post by:
On 2008-06-18 09:41, David wrote: You can have complete history in a database schema by: * adding a version column * adding a modification timestamp (and modification username, if that's...
0
by: eGenix Team: M.-A. Lemburg | last post by:
On 2008-10-15 20:30, Terry Reedy wrote: It's going to look even better when we release version 4.0 in a year or so ;-) FWIW, we're still waiting for the dust to settle before going for a Py3k...
6
by: Carl Banks | last post by:
I was wondering if anyone had any advice on this. This is not to study graph theory; I'm using the graph to represent a problem domain. The graphs could be arbitrarily large, and could easily...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...

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.