473,434 Members | 1,491 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,434 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 5809
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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...
0
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
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...
1
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
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...
0
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
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...
0
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...

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.