Nathan Hinchey
Nathan Hinchey

Reputation: 1201

string interpolation in SQL query: dangerous and/or wrong? (python)

We all know the story of Bobby Tables and not to just use simple string interpolation with strings that come from users.

But what I'm wondering is whether it's OK to use string interpolation from my own hardcoded strings.

For example, I see no way this is dangerous, but I want to make sure. And if it is simply the wrong way to go about it for some non-security reason I'd like to know that, too.

table_dict = {'option1':'table_1','option2':'table_2'}

query_string = "SELECT * FROM {}".format(table_dict[string_from_front_end])

Obviously this is a far simpler example than what I intend to actually do -- my real query is much longer --, but my question is about that string interpolation.

  1. Is it safe?
  2. Is there a better way I should be doing this?

Upvotes: 0

Views: 2023

Answers (1)

ngoue
ngoue

Reputation: 1055

As long as the query will never include user input, then it's fine.

Though I would recommend using an ORM where possible, as they are often written to handle string interpolation.

Upvotes: 1

Related Questions