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. -
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 5826 bartonc 6,596
Recognized Expert Expert
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])
-
bartonc 6,596
Recognized Expert Expert
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])
bartonc 6,596
Recognized Expert Expert
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])
-
-
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. -
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()
-
bartonc 6,596
Recognized Expert Expert
This topic is currently being discussed, so I'm bumping this thread.
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.
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 be invoked
is from inside m1.
Is either style preferred?
Here are two short examples:
Helper function as method:
|
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 simplest form, a BHO is a COM in-
|
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 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...
| |
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 {};
|
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):
"""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...
|
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...
|
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,...
|
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...
| |
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...
|
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...
|
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();...
|
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...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |