0

I'm hoping to create a build a query dynamically that I can populate through paramerters. E.g. Something like:

INSERT INTO Table (Col1, Col2, Col3, ...) VALUES (%s, %s, %s, ...)

Then I want to populate it like shown in How to put parameterized sql query into variable and then execute in Python? :

sql = "INSERT INTO table VALUES (%s, %s, %s)"
args= var1, var2, var3
cursor.execute(sql, args)

Building the query string above should be pretty easy, however I'm not sure how to build the list of args. Once I can do that, the rest should be easy.

2 Answers 2

0

Looks like my question was easier than I thought, it looks like arrays behave like lists in python. The following gave me what I needed:

results = []

results.append("a")
results.append("b")
results.append("c")
results.append("d")

print results

I can use the above to make my arg list.

Sign up to request clarification or add additional context in comments.

Comments

0

I typically use something like this to achieve what you describe:

>>> def prepquery(qrystr, args):
...   # Assumes Qry Str has a %s in it instead of column placeholders.
...   return qrystr % ', '.join('?' * len(args)) # ['%s'] * len(args), depending on DB.
...
>>>
>>> prepquery('Insert Into Table Values (%s)', range(5))
'Insert Into Table Values (?, ?, ?, ?, ?)'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.