0

I have a function, where I get a string as parameter. I want to save this string to a database. So I have a command like:

    sql_command = """INSERT INTO some_table(some_text_row) VALUE (
        '{0}');""".format(some_text)

But the parameter can contain characters like '. So I need to replace this sort of characters. I do this with this function:

    some_text = given_parameter.replace("'", r"\'")

But now comes the strange behavior: Sometimes, I get a result of \\' and sometimes I get a result of \'. I want to have the second one.

To give you more information: The given_parameter is the HTML code of a webpage. I get the HTML code from the library called requests

Does anyone have some tipps?

1
  • FWIW, usually you don't want to do your own string interpolation in sql_commands -- It potentially opens you up to sql injection attacks Commented Mar 9, 2015 at 23:21

1 Answer 1

4

Don't construct the query using string formatting - this is unsafe, you are making it vulnerable to SQL injections.

Instead, parameterize the query and let the mysql driver worry about quotes:

sql_command = """
    INSERT INTO 
        some_table(some_text_row) 
    VALUES 
        (%s)"""
cursor.execute(sql_command, (some_text, ))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That was the solution.

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.