473,659 Members | 3,162 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SQL Helper Functions

bartonc
6,596 Recognized Expert Expert
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 5826
bartonc
6,596 Recognized Expert Expert
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 Recognized Expert Expert
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 Recognized Expert Expert
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 Recognized Expert Expert
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 Recognized Expert Expert
This topic is currently being discussed, so I'm bumping this thread.
Jan 19 '07 #6
bartonc
6,596 Recognized Expert Expert
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
8894
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 be invoked is from inside m1. Is either style preferred? Here are two short examples: Helper function as method:
2
6527
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
5726
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 simplest form, a BHO is a COM in-
1
1362
by: Tran Hong Quang | last post by:
Hello, What is helper function concept? I am new to C. Thanks Tran Hong Quang
1
3228
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 helper functions to convert between the types used, in particular between 'unsigned long long' and a ValidityKey which is like an unsigned long long but only goes up to 2^63 -1. (Please dont flame me for using unsigned long long, I know its not...
6
3525
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 Hidden_functionality { protected: // These helper classes provide some functionality that is // only used by the client classes class Helper1 {};
6
49730
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
4801
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): """Build an SQL SELECT command from the arguments: Return a single string which can be 'execute'd. arglist is a list of strings that are column names to get. argdict and kwargs are two way to evaluate 'colName'=value for the...
0
8428
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8337
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8748
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8628
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7359
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5650
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4175
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1978
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1739
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.