0

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 :)

Pallavi Joshi
  • 245
  • 2
  • 17
  • How are you connecting to the mysql database with python? – Brendan Abel Jan 22 '16 at 07:49
  • 1
    So you want a toggle that changes 'or' to 'and'? – Strawberry Jan 22 '16 at 07:59
  • @BrendanAbel - `code` mysql.connector.connect(user='abc',password='XXX',host = 'localhost',port = 'xyz', database='organisations',buffered=True). – Pallavi Joshi Jan 22 '16 at 09:26
  • @Strawberry - I am not sure whether I have understood your question. But all I want is to accept whichever parameter is passed and use it accordingly in WHERE clause. So while calling the actual function one can send only **student_city** or only **student_stream** or can send both the parameters – Pallavi Joshi Jan 22 '16 at 09:30
  • Ok, so you want to build the query using only passed parameters. Implode passed parameters with 'and'. I'm sure there are lots of python tutorials on this. – Strawberry Jan 22 '16 at 10:01

3 Answers3

2

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.

Pallavi Joshi
  • 245
  • 2
  • 17
0

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

armak
  • 560
  • 5
  • 13
0

Check this thread on parameterized query:

sql search query with multiple optional search parameters

Hope this answers your query :)

Community
  • 1
  • 1