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. -
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 WHERE clause"""
-
a = ', '.join(arglist)
-
args = argdict.copy()
-
args.update(kwargs)
-
for key, value in args.items():
-
args[key] = (str(value), repr(value))[type(value) == str]
-
b = ''
-
if args:
-
b = 'WHERE %s' % ' AND '.join(key + '=' + value
-
for key, value in args.items())
-
return ' '.join(['SELECT', (a or '*'), 'FROM', table, b])
-
6 5809
Here is the next installment: -
-
def MySQLInsert(table, argdict={}, **kwargs):
-
"""Build an SQL INSERT command from the arguments:
-
Return a single string which can be 'execute'd.
-
argdict is a dictionary of 'column_name':value items.
-
**kwargs is the same but passed in as column_name=value"""
-
args = argdict.copy()
-
args.update(kwargs)
-
keys = args.keys()
-
argslist = []
-
for key in keys:
-
a = args[key]
-
argslist.append((str(a), repr(a))[type(a) == str])
-
a = '(%s)' %', '.join(field for field in keys)
-
b = '(%s)' %', '.join(argslist)
-
return ' '.join(['INSERT', table, a, 'VALUES', b])
-
Here's the update converter: -
-
-
def MySQLUpdate(table, valuedict, argdict={}, **kwargs):
-
"""Build an SQL SELECT command from the arguments:
-
Return a single string which can be 'execute'd.
-
valuedict is a dictionary of column_names:value to update.
-
argdict and kwargs are two way to evaluate 'colName'=value
-
for the WHERE clause."""
-
vargs = valuedict.copy()
-
for key, value in vargs.items():
-
vargs[key] = (str(value), repr(value))[type(value) == str]
-
a = 'SET %s' % ', '.join(key + '=' + value
-
for key, value in vargs.items())
-
args = argdict.copy()
-
args.update(kwargs)
-
for key, value in args.items():
-
args[key] = (str(value), repr(value))[type(value) == str]
-
b = ''
-
if args:
-
b = 'WHERE %s' % ' AND '.join(key + '=' + value
-
for key, value in args.items())
-
-
return ' '.join(['UPDATE', table, a, b])
Here's a pretty simplistic delete fuction; -
-
-
def MySQLDelete(table, argdict={}, **kwargs):
-
"""Build an SQL DELETE command from the arguments:
-
Return a single string which can be 'execute'd.
-
argdict and kwargs are two way to evaluate 'colName':value
-
for the WHERE clause."""
-
args = argdict.copy()
-
args.update(kwargs)
-
for key, value in args.items():
-
args[key] = (str(value), repr(value))[type(value) == str]
-
b = ''
-
if args:
-
b = 'WHERE %s' % ' AND '.join(key + '=' + value
-
for key, value in args.items())
-
return ' '.join(['DELETE FROM', table, b])
-
-
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. -
from MySQLdb import *
-
from time import time
-
-
class DBServer:
-
def __init__(self, master):
-
self.master = master
-
-
def Login(self, servername, username, password, database=""):
-
try:
-
self.dbconnect = connect(host=servername, user=username, passwd=password, db=database)
-
except (DatabaseError, OperationalError):
-
self.dbconnect = None
-
self.master.write('Couldn\'t connect to the database named %s on host %s'
-
%(repr(database), repr(servername)))
-
return
-
self.dbcursor = self.dbconnect.cursor()
-
self.Execute('SET autocommit=1')
-
return self.dbconnect
-
-
def DBError(self):
-
"""Remove the current message from the cursor
-
and display it."""
-
try:
-
(error, message) = self.dbcursor.messages.pop()
-
except AttributeError:
-
(error, message) = self.dbconnect.messages.pop()
-
self.master.write('%s #%d: %s' %(str(error).split('.')[-1],
-
message[0], message[1]))
-
-
def Execute(self, query):
-
try:
-
cursor = self.dbcursor
-
now = time()
-
cursor.execute(query)
-
nRows = cursor.rowcount
-
self.master.write(query)
-
self.master.write("%d rows affected: %.2f sec." %(nRows, time() - now))
-
except (DatabaseError, OperationalError):
-
self.DBError()
-
return
-
return cursor
-
-
def DBExists(self, database):
-
"""Return True if database exists"""
-
resultset = self.Execute("show databases").fetchall()
-
## print resultset
-
return (database,) in resultset
-
-
def close(self):
-
self.dbconnect.close()
-
This topic is currently being discussed, so I'm bumping this thread.
This topic is currently being discussed, so I'm bumping this thread.
These have recently been updated in this thread in the Articles section.
Sign in to post your reply or Sign up for a free account.
Similar topics
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...
|
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
{
|
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...
|
by: Tran Hong Quang |
last post by:
Hello,
What is helper function concept? I am new to C.
Thanks
Tran Hong Quang
|
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...
|
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...
|
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 ***
|
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):
...
|
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...
|
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: 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,...
|
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...
|
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...
|
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...
|
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,...
|
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...
|
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...
| |