473,378 Members | 1,543 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

SQL Helper Functions

bartonc
6,596 Expert 4TB
Here is the first installment of SQL helper functions which I use with two classes that I wrote which encapsulate a MySQL server and a MySQL client. These helpers make it easy to convert back and forth between python dictionaries and SQL tables.

Expand|Select|Wrap|Line Numbers
  1. def MySQLSelect(table, arglist=[], argdict={}, **kwargs):
  2.     """Build an SQL SELECT command from the arguments:
  3.     Return a single string which can be 'execute'd.
  4.     arglist is a list of strings that are column names to get.
  5.     argdict and kwargs are two way to evaluate 'colName'=value
  6.     for the WHERE clause"""
  7.     a = ', '.join(arglist)
  8.     args = argdict.copy()
  9.     args.update(kwargs)
  10.     for key, value in args.items():
  11.         args[key] = (str(value), repr(value))[type(value) == str]
  12.     b = ''
  13.     if args:
  14.         b = 'WHERE %s' % ' AND '.join(key + '=' + value
  15.                                      for key, value in args.items())
  16.     return ' '.join(['SELECT', (a or '*'), 'FROM', table, b])
  17.  
Nov 5 '06 #1
6 5793
bartonc
6,596 Expert 4TB
Here is the next installment:
Expand|Select|Wrap|Line Numbers
  1.  
  2. def MySQLInsert(table, argdict={}, **kwargs):
  3.     """Build an SQL INSERT command from the arguments:
  4.     Return a single string which can be 'execute'd.
  5.     argdict is a dictionary of 'column_name':value items.
  6.     **kwargs is the same but passed in as column_name=value"""
  7.     args = argdict.copy()
  8.     args.update(kwargs)
  9.     keys = args.keys()
  10.     argslist = []
  11.     for key in keys:
  12.         a = args[key]
  13.         argslist.append((str(a), repr(a))[type(a) == str])
  14.     a = '(%s)' %', '.join(field for field in keys)
  15.     b = '(%s)' %', '.join(argslist)
  16.     return ' '.join(['INSERT', table, a, 'VALUES', b])
  17.  
Nov 11 '06 #2
bartonc
6,596 Expert 4TB
Here's the update converter:

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. def MySQLUpdate(table, valuedict, argdict={}, **kwargs):
  4.     """Build an SQL SELECT command from the arguments:
  5.     Return a single string which can be 'execute'd.
  6.     valuedict is a dictionary of column_names:value to update.
  7.     argdict and kwargs are two way to evaluate 'colName'=value
  8.     for the WHERE clause."""
  9.     vargs = valuedict.copy()
  10.     for key, value in vargs.items():
  11.         vargs[key] = (str(value), repr(value))[type(value) == str]
  12.     a = 'SET %s' % ', '.join(key + '=' + value
  13.                                  for key, value in vargs.items())
  14.     args = argdict.copy()
  15.     args.update(kwargs)
  16.     for key, value in args.items():
  17.         args[key] = (str(value), repr(value))[type(value) == str]
  18.     b = ''
  19.     if args:
  20.         b = 'WHERE %s' % ' AND '.join(key + '=' + value
  21.                                      for key, value in args.items())
  22.  
  23.     return ' '.join(['UPDATE', table, a, b])
Nov 12 '06 #3
bartonc
6,596 Expert 4TB
Here's a pretty simplistic delete fuction;



Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. def MySQLDelete(table, argdict={}, **kwargs):
  4.     """Build an SQL DELETE command from the arguments:
  5.     Return a single string which can be 'execute'd.
  6.     argdict and kwargs are two way to evaluate 'colName':value
  7.     for the WHERE clause."""
  8.     args = argdict.copy()
  9.     args.update(kwargs)
  10.     for key, value in args.items():
  11.         args[key] = (str(value), repr(value))[type(value) == str]
  12.     b = ''
  13.     if args:
  14.         b = 'WHERE %s' % ' AND '.join(key + '=' + value
  15.                                      for key, value in args.items())
  16.     return ' '.join(['DELETE FROM', table, b])
  17.  
  18.  
Nov 17 '06 #4
bartonc
6,596 Expert 4TB
And here is a class that I call a server because it stores the connection and cursor, handles errors and sends info (last query, etc) to its master's write() command. called with sys.stdout as the master, my dbServer prints to stdout.

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.         try:
  10.             self.dbconnect = connect(host=servername, user=username, passwd=password, db=database)
  11.         except (DatabaseError, OperationalError):
  12.             self.dbconnect = None
  13.             self.master.write('Couldn\'t connect to the database named %s on host %s'
  14.                               %(repr(database), repr(servername)))
  15.             return
  16.         self.dbcursor = self.dbconnect.cursor()
  17.         self.Execute('SET autocommit=1')
  18.         return self.dbconnect
  19.  
  20.     def DBError(self):
  21.         """Remove the current message from the cursor
  22.            and display it."""
  23.         try:
  24.             (error, message) = self.dbcursor.messages.pop()
  25.         except AttributeError:
  26.             (error, message) = self.dbconnect.messages.pop()
  27.         self.master.write('%s #%d:  %s' %(str(error).split('.')[-1],
  28.                                           message[0], message[1]))
  29.  
  30.     def Execute(self, query):
  31.         try:
  32.             cursor = self.dbcursor
  33.             now = time()
  34.             cursor.execute(query)
  35.             nRows = cursor.rowcount
  36.             self.master.write(query)
  37.             self.master.write("%d rows affected: %.2f sec." %(nRows, time() - now))
  38.         except (DatabaseError, OperationalError):
  39.             self.DBError()
  40.             return
  41.         return cursor
  42.  
  43.     def DBExists(self, database):
  44.         """Return True if database exists"""
  45.         resultset = self.Execute("show databases").fetchall()
  46.         ## print resultset
  47.         return (database,) in resultset
  48.  
  49.     def close(self):
  50.         self.dbconnect.close()
  51.  
Nov 29 '06 #5
bartonc
6,596 Expert 4TB
This topic is currently being discussed, so I'm bumping this thread.
Jan 19 '07 #6
bartonc
6,596 Expert 4TB
This topic is currently being discussed, so I'm bumping this thread.
These have recently been updated in this thread in the Articles section.
Oct 18 '07 #7

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

Similar topics

4
by: Robert Ferrell | last post by:
I have a style question. I have a class with a method, m1, which needs a helper function, hf. I can put hf inside m1, or I can make it another method of the class. The only place hf should ever...
2
by: Koen | last post by:
Hi all, I have a question about something rather common, but I'm a bit lost at the moment: Lat's say you have this: // in A.h Class A {
8
by: Joe Johnston | last post by:
I need a Browser Helper object written in VB.NET Please point me at a good example. Joe MCPx3 ~ Hoping this MSDN ng three day turnaround is true. Additional info: What is a BHO? In its...
1
by: Tran Hong Quang | last post by:
Hello, What is helper function concept? I am new to C. Thanks Tran Hong Quang
1
by: shaun roe | last post by:
When should a function be a private member, and when simply a standalone function in the .cpp file? I'm in the middle of writing a class which bridges between two packages, and so I need some...
6
by: mailforpr | last post by:
Suppose you have a couple of helper classes that are used by 2 client classes only. How can I hide these helper classes from other programmers? Do you think this solution is a good idea?: class...
6
by: Mike P | last post by:
I have heard about helper classes, but can somebody please explain to me what they are and what they are used? *** Sent via Developersdex http://www.developersdex.com ***
0
bartonc
by: bartonc | last post by:
Here are the latest versions of My (as in mine) SQL helper functions. Please feel free to rename them if you use them. The SELECT helper:def MySQLSelect(table, arglist=(), argdict={}, **kwargs): ...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
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...

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.