2016-01-22 55 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) 

这是一些什么类似于上述建议。感谢所有的指导。