0

i am writing the following sql query:

"select someTableName.somefield, count(*) from someTableName WHERE someTableName.TimeStamp > %s and someTableName.EndTimeStamp < %s group by someTableName.ProviderUsername;", [from_date, to_data]

this query can be used on three tables, so i do not want to fix the table name so what i am doing is like this.

"select %s.somefield, count(*) from %s WHERE %s.TimeStamp > %s and %s.EndTimeStamp < %s group by %s.ProviderUsername;", [tableName, tableName, tableName, from_date, tableName, to_data, tableName]

as you could see in above query i have to use tableName multiple times so i need to provide tableName for each occurance, is there any best way to achieve this??

Edited

i do not have python 2.6 to use str.format and for some reason can't move to latest versionof python , i am using python version 2.5.2, so what is the best solution in this environment?

1
  • Be very careful that the variables going in to that string aren't unsanitized user-submitted content; this has SQL injection written all over it. Commented Sep 14, 2011 at 13:24

4 Answers 4

5

You can use named variables in string formatting, like this:

"select %(tableName)s.somefield, count(*) from %(tableName)s WHERE %(tableName)s.TimeStamp > %(fromDate)s and %(tableName)s.EndTimeStamp < %(to_data)s group by %(tableName)s.ProviderUsername;" %{'tableName':tableName, 'fromDate':fromDate, 'to_data':to_data}
Sign up to request clarification or add additional context in comments.

Comments

3

If you have at least Python 2.6, you can use str.format:

s = "select {0}.somefield, count(*) from {0} WHERE {0}.TimeStamp > {1} and {0}.EndTimeStamp < {2} group by {0}.ProviderUsername;"
query = s.format(tableName, fromDate, toDate)

That way you can use the same variable multiple times in the string.

Also note that this is more future-proof than the old % formatting.

2 Comments

thanks for response, i have edited my post please read again, i using old python version.
@AamirAdnan: well, you got the answer for that case thrice already... :)
2

You can substitute with a dictionary

mydict = {'table': whatever, 'startdate': yourstartdate, 'enddate': yourenddate}
sql = "select %(table)s.somefield, count(*) from %(table)s WHERE %(table)s.TimeStamp > %(startdate)s and %(table)s.EndTimeStamp < %(enddate)s group by %(table)s.ProviderUsername;" % mydict

Comments

0
template = "select %(tableName)s.somefield, count(*) from %(tableName)s WHERE %(tableName)s.TimeStamp > %(fromDate)s and %(tableName)s.EndTimeStamp < %(to_data)s group by %(tableName)s.ProviderUsername;"
query = template % locals()

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.