473,546 Members | 2,244 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Database Login now uses mxODBC

bartonc
6,596 Recognized Expert Expert
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 4983

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

Similar topics

13
3388
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 front-end needs to be cross- platform (Windows and Linux). Does anyone have any suggestions on what database connectivity I should use? I've looked at...
23
2801
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. Is mySQL a nice start with python ? Sincerely Yours, Pujo
5
3758
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 with Python. My problem is that I keep hitting screwy records with what appears to be a malformed dbiDate object when I insert certain records. I...
4
3025
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 question is how to implement paging, i.e. the 'Next/Prev' NN records without reestablishing a database connection every time I click Next/Prev? Is...
5
1194
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 database (SQLite would suit just fine), but that would require the user to install more packages other than python itself, and that I am trying to avoid....
10
1946
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. There are several reports that are selected using the gui, and each report is a class in the file reports.py. These classes contain a method which...
0
930
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 relevant for you) * updating the version upon INSERT and UPDATE * have a history table for each "live" table that gets filled using a trigger on the...
0
966
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 port of the mx C extensions. -- Marc-Andre Lemburg
6
2902
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 have millions of nodes, and most nodes have a substantial amount of data associated with them. Obviously I don't want a whole such graph in memory...
0
7507
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...
0
7435
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...
0
7698
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. ...
0
7947
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7461
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7794
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...
0
5080
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...
0
3492
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...
0
747
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.