-1

I have a code like the following:

   sql_command='''SELECT Grade From GRADES where Student_Number='''+str(id) +''' AND Course_ID IN'''+(list)
   grades=execute_sql(sql_command,sql_cursor)

where the list is the a list containing elements in the course_id column satisfying a condition (specific course id),

I want to say, select the only grade where the course_id column is the course_id in my list. How do I do that?

3 Answers 3

0

You want to join all elements in the list into one string, e.g.:

sql_command ='''SELECT Grade From GRADES where Student_Number='''+str(id) 
sql_command+=''' AND Course_ID IN ('''+ ','.join(list) + ''')'''
Sign up to request clarification or add additional context in comments.

2 Comments

the list contains tuples, not str.... is it the same thing to do or ?@EricBouwers
That was not clear to me from the question. Assuming that one of the tuple values contains the course id you are interested in you can create a new list with only those values using the answer to this question
0

A couple of things:

  • Assuming ID is coming from a user's input, this script is going to have being vulnerable to a SQL injection attack. See here for an example of using parameters, which are safer.
  • The solution to your specific question involves imploding your list:

    format_strings = ','.join(['%s'] * len(list))

Source: imploding a list for use in a python MySQLDB IN clause

Comments

0

Here is how it can be done using sqlite3

cursor.execute(
    "SELECT Grade From GRADES where Student_Number= ? AND Course_ID IN (?)",
    (id, ','.join(map(str, list)))
)

Please don't use %s as its not recommended. Check sqlite3 documentation for more.

1 Comment

the list contains tuple,not str, is it the same thing to write?@Stephan

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.