Pallavi Joshi
Pallavi Joshi

Reputation: 245

how to form this mysql select query using python-2.7

I am using Python-2.7 and mysql database and wish to retrieve data from table student using select statement by passing either 2 or any one of 2 parameters as below-

SELECT * FROM student_details where student_city='some_City' or student_stream='Science' or both

parameters will be passed to that function which operated the SELECT statement.

Guidance / Help in any form to make me understand how can I code the where clause part. I don't want to make separate queries.

Apologies if I am asking the question incorrectly or repeating the question. Thanks in advance :)

Upvotes: 0

Views: 812

Answers (3)

Pallavi Joshi
Pallavi Joshi

Reputation: 245

I tried and finally this works for me-

 try:
        query = ("""SELECT * FROM student_details  WHERE """)
        if city is not '0' and Stream == '0':
              complete_query = query+("""student_city = %s""")

        elif Stream is not '0' and city == '0':
            complete_query = query+("""student_stream = %s""")

        else:
            complete_query = query+("""student_city = %s AND student_stream = %s""")

        if city is not '0' and Stream == '0':
            s_execute = self.cur2.execute(complete_query,(city,))

        elif Stream is not '0' and city == '0':
            s_execute = self.cur2.execute(complete_query,(Stream,))

        else:
            s_execute = self.cur2.execute(complete_query,(city),(Stream))
 except MySQLdb.Error as error:
                                print(error)

It was some what similar to above suggestion. Thanks all for guiding.

Upvotes: 2

Nirav Bajaj
Nirav Bajaj

Reputation: 1

Check this thread on parameterized query:

sql search query with multiple optional search parameters

Hope this answers your query :)

Upvotes: 0

armak
armak

Reputation: 560

use a python wrapper around MySQL and use execute() to run whatever you want.For details follow this link

http://www.tutorialspoint.com/python/python_database_access.htm

Upvotes: 0

Related Questions