3

I am trying to return a numeric value from this statement:

c = db.execute("""SELECT *, rowid FROM members WHERE barcode = '%s' AND debit > 0 LIMIT 50""" % (s,))

But I get this as the returned value:

sqlite3.Cursor object at 0xb6cb2720

What should I do with this cursor object to get the results?

2
  • Have you tried enumerating c? for row in c: ... Commented Sep 4, 2014 at 0:26
  • 2
    To retrieve data after executing a SELECT statement, you can either treat the cursor as an iterator, call the cursor’s fetchone() method to retrieve a single matching row, or call fetchall() to get a list of the matching rows. Commented Sep 4, 2014 at 0:27

4 Answers 4

4

Try this:

for row in c:
    print row['rowid']
Sign up to request clarification or add additional context in comments.

8 Comments

Directly enumerating c instead of c.fetchall() will require less memory since the entire result set isn't loaded into memory all at once, rather each row would be loaded in one at a time and discarded before the next.
Updated. Thanks for the tip. This is why I love answering questions on SO. My way of thinking is validated or not and either way, I learn something.
@cdhowie actually SQLite will not necessarily return the entire result set, but it certainly buffers some in memory before returning the next set from a transactional log on disk (unless it's an in-mem DB)... But yes, still certainly more efficient than list'ing or .fetchall'ing the results.
@JonClements Of course. Buffering is good for performance. But the DB engine knows how much it should buffer to perform better; pulling the entire set into memory is likely to be much worse.
@cdhowie the slight trade off being that if it's "not that large" - than requesting the whole lot is often more efficient (doesn't require transactional locks and logs for so long) than requesting chunks... but I'm going off-topic here :)
|
0

try this>>print(cursorObject.fetchone()[0])

Comments

0

I just convert to list of tuples

sql="SELECT *, rowid FROM members WHERE barcode = '%s' AND debit > 0 LIMIT 50" % (s,)
c = list(db.execute(sql)

Comments

0

One of my problems was, I was using the wrong SQL query to get the data I wanted. See:

c = db.execute("""SELECT "debit" FROM "members" WHERE "barcode" = '%s' LIMIT 1""" % (s,))

I would then get the response:

(0,)

Which was what I needed. Now to actually work out how to compare it - I need to say "if c is not equal to (0,) then print 'cross' else print 'tick'..."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.