2016-01-22 57 views
0

我使用Python的2.7和MySQL數據庫,並希望通過將2個或爲如下─如何使用,形成這個MySQL選擇查詢的python-2.7

2個參數的任何一個檢索使用SELECT語句從表學生資料

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

參數將傳遞給操作SELECT語句的那個​​函數。

指導/幫助以任何形式讓我明白如何編碼where子句部分。 我不想單獨進行查詢。

道歉,如果我不正確地問問題或重複問題。感謝提前:)

+0

你如何使用python連接到mysql數據庫? –

+1

所以你想要一個切換'或'到'和'? – Strawberry

+0

@BrendanAbel - 'code' mysql.connector.connect(user ='abc',password ='XXX',host ='localhost',port ='xyz',database ='organizations',buffered = True)。 –

回答

0

使用MySQL周邊蟒蛇包裝和使用execute()運行任何你want.For詳細信息請點擊此鏈接

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

+0

我知道我在問如何使用WHERE子句來處理兩個參數之間的差別,其中一個參數可能是可選的,也可能不是可選的。 –

+0

執行方法使用raw_query只是將查詢作爲字符串傳遞。 – armak

2

我試着最後這適用於我 -

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) 

這是一些什麼類似於上述建議。感謝所有的指導。