Question

I need to call a Stored Procedure in python. The wrapper function accepts n number of parameters. Based on the parameter list, I need to quote or unquote the arguments. I also need to send a null parameter.

How can I iterate through the function argument and build the SQL string?

for eg. the stored proc call looks like this - SP_TEST('chrA',intB,chrC)

def execSp(a,b,c,d):
    <iterate through params and build param list>
    #If the parameter c is null the SQL should be built as below
    SQL="exec SP_TEST('a',b,Null)";

I tried using locals() however it returns an unordered list

Am new to python so any leads will be of great help.

Was it helpful?

Solution

The following does exactly what you want. It starts by initializing the list AV to all NULL, then iterates of the number of arguments supplied, and replaces them appropriately to form the query string that you wanted. The SQL = string adds quotes to the first argument only. Did I understand correctly what you were trying to do?

def execSp(*args):
  AV = []
  SQL = "exec SP_TEST(";
  for ii in range(0,4) :
    AV.append("NULL");
  ii = 0;

  for a in args:
    AV[ii] = str(a);
    ii+=1;

  SQL = SQL + "\'" + AV[0] + "\'," + AV[1] + "," + AV[2] + "," + AV[3] + ")";
  print SQL

execSp("hello", 1, 2, 3);
execSp("hi", 2, 3);

When I run this, I get

exec SP_TEST('hello',1,2,3)
exec SP_TEST('hi',2,3,NULL)

OTHER TIPS

You could use the *args construct:

In [1]: def execSp(*args): print args

In [2]: execSp('abc', 1, 'xyz')
('abc', 1, 'xyz')

You can do something like this:

def execSp(*args):
    if len(args) != 4:
        raise SomeException()
    a,b,c,d = args
    <you can now iterate over args and use a,b,c,d as required>
>>> def f(*args):
...   for a in args:
...     print a
... 
>>> f(1, 2, 3, 4)
1
2
3
4

Do you need to build your own query? Usually, you would rely on the DB api to quote your arguments for you. This will avoid you suffering from SQL injection.

cursor.execute('exec SP_TEST(?, ?, ?)', a, b, c)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top