Discussion:
[Tutor] if/then statement and sql count rows
Spencer For Friends
2015-04-30 02:59:48 UTC
Permalink
Hi All,

I'm attempting to perform an if then statement based on the results of a
sql count rows query. The query is returning the proper values however the
if/then statement seems to be ignoring the returned value of the sql
statement.

Here is my code.

import sqlite3

# Define SQL statement to select all Data from Column Name
sql = "SELECT Count(*) FROM arbtable WHERE Name = ?"

book_name = 'Winged Coat'

class PriceCheck(object):
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.c = self.conn.cursor()


def query(self, arg, cardname):
self.c.execute(arg, cardname)
return self.c

def __del__(self):
self.conn.close()

def display():
#Connect To DB and Get Price of Matched book.
getbookprice = PriceCheck("arbbase.sqlite")
for row in getbookprice.query(sql, ([book_name])):
if row == 0:
print 'no row was found'
else:
print 'Yep its there!'
print row



display()

The program here is that my result, as evidenced by "print row" at the
bottom of the code is 0. Since it is zero according to my if statement it
should print 'no row was found', but instead it prints the else statement
value of 'yes its there!'

I've researched extensively and think that possibly the fetchone statement
is what I need, but I can't seem to figure out how to properly apply this
to my code to test it.

Any help would be highly appreciated.

Thank you kindly

Sour Jack
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Alan Gauld
2015-04-30 08:46:49 UTC
Permalink
Post by Spencer For Friends
self.conn = sqlite3.connect(db)
self.c = self.conn.cursor()
self.c.execute(arg, cardname)
return self.c
You are returning the cursor object here.
That's probably not what the user of your code wants,
it would be better to return the actual result.
You can get that using fetchone() or fetchall()
Since count() can only return one value fetchone()
would be best here.

return self.c.fetchone()
Post by Spencer For Friends
self.conn.close()
#Connect To DB and Get Price of Matched book.
getbookprice = PriceCheck("arbbase.sqlite")
Insert a debug statement here:

print type(row), ':', row

And see if what you get is what you expect.
Post by Spencer For Friends
print 'no row was found'
print 'Yep its there!'
print row
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Continue reading on narkive:
Loading...