473,320 Members | 1,965 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,320 developers and data experts.

SQL helper function updates

bartonc
6,596 Expert 4TB
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 4782

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...
4
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
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
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
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.