Python Forum

Full Version: SQL wild card use
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to use a " * " in a a SQL WHERE clause passed in as an argument. The reason is to return the last entered tagNo if they do not know the other two search criteria.
I get no returns with the use of the '*' but do when I pass he exact match for all three WHERE criteria. Can you use wild cards the way i am trying to use them?

            tagNo=self.cow_detBtn['tag'].text
            tagClr=self.cow_detBtn['tagClr'].text
            tagYr=self.cow_detBtn['tagYr'].text
            if tagNo!='' and tagClr!='' and tagYr!='':
                cow=self.db.searchCow(tagNo,tagClr,tagYr)
            elif tagNo!='' and tagClr!='' and tagYr=='':
                cow=self.db.searchCow(tagNo,tagClr,'*')
            elif tagNo!='' and tagClr=='' and tagYr!='':
                cow=self.db.searchCow(tagNo,'*',tagYr)
            elif tagNo!='' and tagClr=='' and tagYr=='':
                cow=self.db.searchCow(tagNo,'*','*')

def searchCow(self,tagNo,tagClr,tagYr):
        self.c.execute('SELECT * From cowTbl where tagNo=? and tagClr=? and tagYr=? LIMIT 1',(tagNo,tagClr,tagYr))
        cows=self.c.fetchall()
        return cows
May could do something like:

def searchCow(self,tagNo,tagClr,tagYr):
    if tagNo and tagClr and tagYr:
        # All args are true, pull this record
        self.c.execute('SELECT * From cowTbl where tagNo=? and tagClr=? and tagYr=? LIMIT 1',(tagNo,tagClr,tagYr))
    elif tagNo or tagClr or tagYr:
        # Atleast one arg is true, pull this recored
        self.c.execute('select * from cowTbl where tagNo=? or tagClr=? or tagYr=? limit 1',(tagNo,tagClr,tagYr))
    else:
        # All args are empty pull the last record entered
        self.c.execute('select * from cowTbl order by tagNo desc limit 1')
    cows=self.c.fetchall()
    return cows
Wildcard characters in SQL are underscore ( _ ) for one character and percent ( % ) for zero or more characters. BUT when you use a wildcard character you must not use de equals ( = ) operator, but the "LIKE" operator.
select * from cowTbl where tagClr LIKE 'blac%);
This only goes for character fields, not numbers.
Thanks all.
Gives me something to work with.