1

I have this method that creates the query and passes two string parameters. But when I test this it has escape characters '' before the single quote '''.

The query can only accept native queries in string form

I also tried string.replace method but doesnt work

replace('\\', '')

Here is the code

def update_query(self, status, row_id):
    return '''UPDATE TABLE SET STATUS = {0} WHERE ID = {1}'''.format(status, row_id)

Here is the sample output:

'UPDATE TABLE SET STATUS = 'Success' WHERE ID = 1'

Thank you

3 Answers 3

3

I think you absolutely should be using prepared statements here, which the other answers don't seem to be recommending (for whatever reason). Try using something along these lines:

sql = "UPDATE TABLE SET STATUS = :status WHERE ID = :id"
cursor.prepare(sql)
cursor.execute(None, {'status':status, 'id':row_id})

One advantage of using prepared statements here is that it frees the user from having to worry about how to properly escape the literal placeholders in the query. Instead, we only need to bind a variable with the correct type to the statement, and Oracle will handle the rest.

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

1 Comment

Hi Tim, I am using a helper class to execute db queries that only accepts native queries in string form.
2

You can also use f-string for formatting your string


def update_query(self,status, row_id):
    return f"UPDATE TABLE SET STATUS = '{status}' WHERE ID = {row_id}"

>>> update_query("Success",1)
"UPDATE TABLE SET STATUS = 'Success' WHERE ID = 1"

1 Comment

I am using an older version of python, this is not applicable.
1

you need to add \ in the code

def update_query(self, status, row_id):
    return '''UPDATE TABLE SET STATUS = \'{0}\' WHERE ID = {1}'''.format(status, row_id)

2 Comments

the backslash (\) isn't necessary.
adding backslash will not recognize the first bind variable

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.