0

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 "<br>", 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

4

1 回答 1

1

杰里米,

为了回答您的问题,Martijn 在这里做了很好的解释:

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.年龄,自我。性别))

但是,在您的情况下,最好的办法是使用 ORM。从长远来看,这将为您节省很多麻烦!

编写自己的 SQL 查询很好,但是,您会遇到几个问题。基于 SQL 的攻击,以及更难解析数据,是两种。

关于 ORM 的一般信息:http ://en.wikipedia.org/wiki/Object-relational_mapping

对于 Python,有一些不错的。SQLAlchemy 是最知名的,但看看周围,看看你需要什么。

于 2013-11-13T12:37:12.660 回答