python有条件查询mysql_如何在单个sql查询中编写多个条件以获取数据-Python mysql

I am in a dilema that how could i writ such sql queries to make a seach. I have tried and posted it, but it not as expected when user enter data in multiple field of a form and make a search.

The query which i wrote form for a single form field and makes a search and display

#!/usr/bin/python

import cgi

import MySQLdb

class Table():

def __init__(self, host, user, passwd, name):

self.db = MySQLdb.connect(host = host, user = user, passwd = passwd, db = name)

self.cursor = self.db.cursor()

def getdata(self, fname, lname, age, gender):

self.fname = fname

self.lname = lname

self.age = age

self.gender = gender

def mysqlconnect(self):

sql = "select * from PERSON where F_Name = '%s' or L_Name = '%s' or Age = '%s' or Gender = '%s' " %(self.fname, self.lname, self.age, self.gender)

self.cursor.execute(sql)

result = self.cursor.fetchall()

for row in result:

print "
", row[0], row[1], row[2], row[3]

self.cursor.close()

self.db.close()

def main():

print "Content-type: text/html\n"

tableobj = Table("localhost", "root", "root", "Info")

form = cgi.FieldStorage()

f_name = form.getvalue('firstname', '')

l_name = form.getvalue('lastname', '')

age = form.getvalue('age', 0)

gender = form.getvalue('gender', '')

tableobj.getdata(f_name, l_name, age, gender)

tableobj.mysqlconnect()

if __name__ == "__main__":

main()

If suppose user enter data into FirstName field and in the Gender Field

Firstname: Jeremy

Gender: male

then it should display the record.

If supposer user enter data in Age field and Gender field

Age : 25

Gender: Female

It should display result of fewmale whose age is 25.

Likewise all the possible condition

解决方案

Jeremy,

To answer your question, Martijn did a great job of explaining here:

sql = "select * from PERSON where F_Name = %s or L_Name = %s or Age = %s or Gender = %s", > then self.cursor.execute(sql, (self.fname, self.lname, self.age, self.gender))

But, in your case, the best idea would be to use an ORM. This would save you a lot of trouble in the long run!

Writing your own SQL queries is fine, however, you open yourself to several problems. SQL-based attacks, as well as just having a harder time parsing your data, are two.

For Python, there are a few good ones. SQlAlchemy is the most known, but look around and see what you need.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值