473,503 Members | 2,152 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SQL helper function updates

bartonc
6,596 Recognized Expert Expert
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:
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.     # Allow NULL columns in the result set # pyodbc makes rows mutable so, use it!
  8.     a = ', '.join((arg, 'NULL')[arg is None] for arg in arglist)
  9.     args = argdict.copy()
  10.     args.update(kwargs)
  11.     for key, value in args.items():
  12.         args[key] = (str(value), repr(value))[isinstance(value, str)]
  13.     b = ''
  14.     if args:
  15.         b = 'WHERE %s' %' AND '.join(key + '=' + value
  16.                                      for key, value in args.items())
  17.  
  18.     return ' '.join(['SELECT', (a or '*'), 'FROM', table, b])
The INSERT and UPDATE helpers now convert None to NULL:
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()   # don't modify caller dictionary!
  8.     args.update(kwargs)
  9.     keys = args.keys() # an ordered list #
  10.     argslist = []
  11.     for key in keys:
  12.         a = args[key]  # argslist will match the order from above #
  13.         argslist.append(((str(a), repr(a))[isinstance(a, str)], "NULL")[a is None])
  14.     # wrap comma separated values in parens
  15.     a = '(%s)' %', '.join(field for field in keys)
  16.     b = '(%s)' %', '.join(argslist)
  17.     return ' '.join(['INSERT', table, a, 'VALUES', b])
  18.  
  19.  
  20. def MySQLUpdate(table, valuedict, argdict={}, **kwargs):
  21.     """Build an SQL SELECT command from the arguments:
  22.     Return a single string which can be 'execute'd.
  23.     valuedict is a dictionary of column_names:value to update.
  24.     argdict and kwargs are two way to evaluate 'colName'=value
  25.     for the WHERE clause."""
  26.     vargs = valuedict.copy()
  27.     for key, value in vargs.items():
  28.         vargs[key] = ((str(value), repr(value))[type(value) == str], "NULL")[value is None]
  29.     a = 'SET %s' % ', '.join(key + '=' + value
  30.                                   for key, value in vargs.items())
  31.     args = argdict.copy()
  32.     args.update(kwargs)
  33.     for key, value in args.items():
  34.         args[key] = (str(value), repr(value))[type(value) == str]
  35.     b = ''
  36.     if args:
  37.         b = 'WHERE %s' % ' AND '.join(key + '=' + value
  38.                                       for key, value in args.items())
  39.  
  40.     return ' '.join(['UPDATE', table, a, b])
Oct 18 '07 #1
0 4791

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

Similar topics

4
8882
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...
4
5608
by: Rahul Anand | last post by:
Getting SQL Exception when trying to implement Connection based Trasaction using SQL Helper class. I am using the follwing function to execute my stored procs: -=-=-=- ExecuteScalar(ByVal...
1
1848
by: D. Shane Fowlkes | last post by:
Hello All. I keep asking for help with this on the www.asp.net forums and nobody seems to be able to help. What I'm trying to accomplish is very simple. I simply want to create a Hyperlink...
1
1594
by: D. Shane Fowlkes | last post by:
Hey guys. I have a Repeater and a Template. One of the dataitems calls a helper function. The dataitem sends the record ID to the function and the function runs a complex query and returns a...
8
5716
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
1316
by: Tran Hong Quang | last post by:
Hello, What is helper function concept? I am new to C. Thanks Tran Hong Quang
1
3212
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
3519
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...
0
7205
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
7287
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
7349
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...
1
7008
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
5594
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
3177
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...
0
3168
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
746
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
399
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...

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.