0

Probably, my question sounds strange! However, I need this SQL query in Python:

cursor.execute("SELECT TABLE_NAME AS TABLE FROM M_CS_TABLES WHERE SCHEMA_NAME = 'TEST' ")

Since 'TEST' schema changes I need a query like that:

schema_name = 'TEST'
cursor.execute(" SELECT TABLE_NAME AS TABLE FROM M_CS_TABLES WHERE SCHEMA_NAME = " + str(schema_name))

But the output of this line will be:

' SELECT TABLE_NAME AS TABLE FROM M_CS_TABLES WHERE SCHEMA_NAME = TEST'

Not:

" SELECT TABLE_NAME AS TABLE FROM M_CS_TABLES WHERE SCHEMA_NAME = 'TEST' "

What is needed.

I would be appreciated for your help.

0

2 Answers 2

2

this is rather basic SQL practice. NEVER concatenate the string like that.

for your case the best way to do it is just:

schema_name = 'TEST'
cursor.execute("SELECT TABLE_NAME AS TABLE FROM M_CS_TABLES WHERE SCHEMA_NAME = %s", schema_name)

http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries

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

6 Comments

This answer is better than mine.
Thank you for your answer, but I receive this error: hdbcli.dbapi.ProgrammingError: (0, 'Invalid parameters : execute(SELECT TABLE_NAME AS TABLE FROM M_CS_TABLES WHERE SCHEMA_NAME = %s, TEST, {})')
@Vahid which library are you using? for different libraries sometimes they use different placeholders. so instead of %s, it might be ? or {}.
@fahyikyong Regardless of library, When I run this code in Python 3.6: >> schema_name = 'TEST', >> "SELECT TABLE_NAME AS TABLE FROM M_CS_TABLES WHERE SCHEMA_NAME = %s", schema_name, output is: ('SELECT TABLE_NAME AS TABLE FROM M_CS_TABLES WHERE SCHEMA_NAME = %s', 'TEST')
But when I run this one: >> schema_name = " 'TEST' ", >> "SELECT TABLE_NAME AS TABLE FROM M_CS_TABLES WHERE SCHEMA_NAME = {} ".format(schema_name), output is: "SELECT TABLE_NAME AS TABLE FROM M_CS_TABLES WHERE SCHEMA_NAME = 'TEST' "
|
1

You could wrap 'TEST' in another pair of quotes, i.e. use '"TEST"'.

Better yet, insert 'TEST' by using str.format.

>>> schema_name = 'TEST'
>>> 'blablabla "{}"'.format(schema_name)
'blablabla "TEST"'

1 Comment

I just add it to your answer: >>> schema_name = 'TEST' >>> "blablabla '%s' " %schema_name , it has also the same output: "blablabla 'TEST' "

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.