0

I need to use code saved in a string (tmp_str) inside .format ?

tmp_str="ID='ID_VAR_DICT'"
    
sql_text="SELECT FIELD FROM TABLE_A WHERE ID = {ID}"
sql_query = sql_text.format(ID='ID_VAR_DICT')
print ('sql_query -->',sql_query) #Print A
    
sql_query = sql_text.format(eval(tmp_str))
print ('sql_query -->',sql_query) #Print B

Basically I need #Print B to output the same as #Print A but passing the contents off tmp_str to .format

Output:

('sql_query -->', 'SELECT FIELD FROM TABLE_A WHERE ID = ID_VAR_DICT')
Traceback (most recent call last):
  File "_testes.py", line 7, in <module>      
    sql_query = sql_text.format(eval(tmp_str))
  File "<string>", line 1
    ID='ID_VAR_DICT'

Thanks in advance, M

1
  • 3
    Do not use string formatting to create SQL queries. Do something like cursor.execute('SELECT FIELD FROM TABLE_A WHERE ID=?', ('ID_VAR_DICT',)). Commented Mar 1, 2022 at 17:55

1 Answer 1

1

This isn't a recommendation -- as chepner says in a comment, you should use a prepared statement with parameters.

But if you really need to do it your way, you have to eval the entire expression, not just the argument.

sql_query = eval(f'sql_text.format({tmp_str})')
Sign up to request clarification or add additional context in comments.

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.