Python Forum
SQL Query is not executing WHERE clause
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
SQL Query is not executing WHERE clause
#1
I am not getting an error with a Query but it seems to not recognize WERE clause because it returns every row regardless. See listBy_Loc method below where i pass it a parameter for the Select statement. The parameter indicates it is passed to the Select statement on the debug screen (hover over loc )but regardless of what it is, the query returns ALL. I have four possible Loc entries but have inputted data with just one location present at this time but the sort by the other three locations return ALL rows as well. I have checked the table with DB Browser and know the Loc field has only one location name for all it's entries. does anyone see anything wrong with SELECT statement?

#con=sqlite3.connect('bovine.db');
#c=con.cursor();
#c.execute(""" CREATE TABLE cattleData
#           (tagNo integer,
#            Loc text,
#            sex text,
#            type text)
#           """)
#c.execute(""" CREATE TABLE locations
#           (locName text)
#           """);



opList=["Location","Add","Edit"]


class MyDataBase:
    def __init__(self,db_path):
        self.db_path=db_path

    def connect(self):
        self.con=sqlite3.connect(self.db_path)
        self.c=self.con.cursor()
    
    def listBy_Loc(self,loc):
        self.c.execute('SELECT * FROM cattleData WHERE Loc = loc;')
        cattle=self.c.fetchall()
        return cattle

    def locationList(self):
        self.c.execute('''SELECT * FROM locations;''')
        records=self.c.fetchall()
        return records

class MyApp(TabbedPanel):
    def __init__(self,data_base,myCow):
        super(MyApp, self).__init__()
        self.db=data_base
        self.do_default_tab=False
        self.myCow=myCow
 
        for i in opList:
            myTPHM=TabbedPanelHeader()
            myTPHM.text=str(i)
            self.add_widget(myTPHM)
            if str(i)=='Location':
                myTPLoc=TabbedPanel()
                myTPLoc.do_default_tab=False
                myTPHM.content=myTPLoc
                #for j in locList:
                for row in self.db.locationList():
                #self.locationList():
                    #locationName=str(j)
                    myTPHL=TabbedPanelHeader()
                    myTPHL.text=row[0]
                    myTPLoc.add_widget(myTPHL)
                    stkLoc=StackLayout(orientation='tb-lr',spacing=4)
                    myTPHL.content=stkLoc
                    ### add animals to loc tab
                    for row2 in self.db.listBy_Loc(row[0]):
                        tagNo=row2[0]
                        sex=row2[2]
                        bredBy='Shadow'
                        calfTag='55'
                        Cow=myCow(tagNo,sex,bredBy,calfTag)
                        Cow.bind(on_press=self.cowBtn_Press)
                        #
                        stkLoc.add_widget(Cow)
                        #...
                
            if str(i)=='Add':
                myTPHM.content=self.enterScreen()
        
        
    
Reply
#2
This self.c.execute('SELECT * FROM cattleData WHERE Loc = loc;') is wrong. You have your variable in the quotes.

Try using fstring. self.c.execute(f'SELECT * FROM cattleData WHERE Loc = {loc};')
or do it this way self.c.execute('SELECT * FROM cattleData WHERE Loc = ' + loc)
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
Thanks- i made the changes and understand now why that is. However
I now have below error
I have three rows of data in this table where the Loc column is "Hermas" for all three. This is also the parameter passed.
I do not fully understand below. Loc is the column name, not Hermas????


Error:
Exception has occurred: OperationalError (note: full exception trace is shown but execution is paused at: build) no such column: Hermas File "/home/mark/Python Environments/FirstEnvProject/Bovine2.py", line 47, in listBy_Loc self.c.execute('SELECT * FROM cattleData WHERE Loc = ' + loc) File "/home/mark/Python Environments/FirstEnvProject/Bovine2.py", line 85, in __init__ for row2 in self.db.listBy_Loc(row[0]): File "/home/mark/Python Environments/FirstEnvProject/Bovine2.py", line 179, in build (Current frame) return MyApp(my_db,myCow) File "/home/mark/Python Environments/FirstEnvProject/Bovine2.py", line 183, in <module> CreateApp().run()
Reply
#4
(Nov-15-2021, 02:22 AM)menator01 Wrote: Try using fstring.

Please don't suggest this (or string concatenation) - SQL queries should make use of placeholders ("prepared statements"), so as not to be vulnerable to SQL injection. See Bobby Tables.
menator01 likes this post
Reply
#5
Hi mate, there are two possible causes that I can think of that are causing the above errors. Try something similar to the below, but look at bobby tables as suggested above to make sure it's protected.

self.c.execute('select * from cattleData where Loc = '%{loc}%')
See if that works. I believe in your one it is trying to find where the Loc column matches the data in the Hermas column. Don't use my suggestion exactly, I just want to give you an idea, read bobby tables as I was doing this the wrong way and dropped a table during testing.

Thanks,
James
while dad_has_cigs == True:
    happiness = True
    if dad_has_cigs == False:
    print("Dad come home!")
    happiness = not happiness
    break
Reply
#6
Hi @hammer,
I don't see 'Hermas' in your code but I think it is string data to be selected.
First something about syntax: string data must be in single quotes. So the correct syntax is:
"SELECT * FROM cattleData WHERE Loc = 'Hermas'"
So if you choose to use f-string ( which is deprecated, see Bobby Tables) you should do:
columnvalue = "Hermas"
f"SELECT * FROM cattleData WHERE Loc = '{columnvalue}'"
But it is better to use a placeholder. In this case you need not use the single quotes. But you need to give the value as a tuple: (columnvalue,). (Note the comma!)
columnvalue = "Hermas"
self.c.execute("SELECT * FROM cattleData WHERE Loc = ?", (columnvalue,))
( @jamesaarr : when you want to use the wildcard character "%" you need to use "like" instead of "=".
self.c.execute(f"select * from cattleData where Loc like '%{loc}%'")
)
Reply
#7
(Nov-15-2021, 11:44 AM)ibreeden Wrote: Hi @hammer,
I don't see 'Hermas' in your code but I think it is string data to be selected.
First something about syntax: string data must be in single quotes. So the correct syntax is:
"SELECT * FROM cattleData WHERE Loc = 'Hermas'"
So if you choose to use f-string ( which is deprecated, see Bobby Tables) you should do:
columnvalue = "Hermas"
f"SELECT * FROM cattleData WHERE Loc = '{columnvalue}'"
But it is better to use a placeholder. In this case you need not use the single quotes. But you need to give the value as a tuple: (columnvalue,). (Note the comma!)
columnvalue = "Hermas"
self.c.execute("SELECT * FROM cattleData WHERE Loc = ?", (columnvalue,))
( @jamesaarr : when you want to use the wildcard character "%" you need to use "like" instead of "=".
self.c.execute(f"select * from cattleData where Loc like '%{loc}%'")
)
Hi mate,

You're absolutely correct, I was offering a hint rather than the answer ;)

Thanks
while dad_has_cigs == True:
    happiness = True
    if dad_has_cigs == False:
    print("Dad come home!")
    happiness = not happiness
    break
Reply
#8
Problem Resolved- Thanks all for the insight. I used the PLACEHOLDER style suggestion. I have been using that style on INSERT but not SELECT. I need to research more about why/when using placeholders is important.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to use the LIKE clause in Python Columbo 9 1,619 Oct-09-2022, 10:22 PM
Last Post: Larz60+
  How does this if clause work? Pedroski55 3 2,263 Jun-10-2021, 06:31 AM
Last Post: Gribouillis
  can i raise an exception in a try clause? Skaperen 14 5,714 Dec-19-2019, 12:29 AM
Last Post: Skaperen
  pass captured value from input() to where clause metro17 5 3,264 Sep-09-2019, 05:24 AM
Last Post: metro17
  finally clause Skaperen 6 3,872 Jun-02-2019, 09:02 PM
Last Post: snippsat
  if clause fails DeadCthulhuWaitsDreaming 10 4,746 Apr-07-2019, 09:19 PM
Last Post: DeadCthulhuWaitsDreaming
  how to code in Python "where" clause of SAS FelixS 2 2,784 Mar-26-2019, 04:59 PM
Last Post: FelixS
  break Statements and else Clause on Loops Phytonnewbie 2 2,787 Mar-02-2018, 09:50 AM
Last Post: buran
  My else clause doesn't work (general help) NMW 10 7,903 Jul-17-2017, 01:07 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020