-1

I am confusing how can I code in Python.

Following code works from pgsql command line.

select * from consultation_tbl where consultation_status in ('S','C','R');

But in Python, I have no idea how to code.

chat_str = "\'S\',\'C\',\'R\'"
cursor.execute(" \
        SELECT * FROM consultation_tbl
        WHERE consultation_status IN ( %s )", [chat_str])

Please give me an advice.

2
  • 1
    String substitution could lead to SQL Injection attacks. Commented Oct 12, 2017 at 13:53
  • Possible duplicate of SQL query with variables in python Commented Oct 12, 2017 at 14:10

2 Answers 2

1

Firstly, you can use single quotes within double quotes string, This is a valid Python literal string:

chat_str = "'S', 'C', 'R'"

But I would code like this:

# 1) This joins the tokens with ', ' separator. Very useful
chat_str = ', '.join(["'S'", "'C'", "'R'",])

# 2) We use the python3 format() method for strings. 
# The '{}' is replaced. See the official docs
query = "SELECT * FROM consultation_tbl
    WHERE consultation_status IN ({})".format(chat_str)

cursor.execute(query)

In both cases, the result string is equivalent.

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

9 Comments

Thank you for an advice. But I got following error. django.db.utils.ProgrammingError: column "s" does not exist LINE 1: ...ation_tbl WHERE consultation_status IN (S, C, R) How can I fix it?
It seems like you have %s in your code and not the {} placeholder
Thhank you for reply. I use {} in my code. I copy your code and paste it. What is wrong?
Have you debugged this for checking which is the result string? I need to see what is getting postgresql.
I may have to use %s if I use postgresql. "{}" doesn't work in my code.
|
0

Typically you don't want to put data into the query using hand-rolled sting substitution -- the python sql api lets you pass in a tuple which it will sanitize and put in for you to prevent sql injection. That being said since the list of parms in the IN clause can be dynamic in length you may still need string substitution to create a template query. I've usually seen it look something like this:

char_list = ['S', 'C', 'R' ]
qry = "SELECT * FROM consultation_tbl WHERE consultation_status IN ( %s )"
qry %= ",".join("%s" for x in range(len(char_list)))

cursor.execute(qry, chars)

1 Comment

Thank you for an advice. Where chars come from ?

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.