Single row and multi-row fetch (fetchone(), fetchall())

एक SELECT के बाद, fetchone() अगली row को एक tuple के रूप में थमाता है (या ख़त्म होने पर None) जबकि fetchall() बाक़ी हर row को एक list के रूप में थमाता है, और दोनों जो return करते हैं उसे consume कर लेते हैं।

9 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Receptionist के पास आपका जवाब है। अब इसे collect कीजिए।

पिछला lesson एक cliffhanger पर ख़त्म हुआ: cur.execute("SELECT roll, score FROM marks") ठीक चला, पर कोई भी row कहीं नहीं दिखी।

यह design से है। execute() सिर्फ़ results को cursor पर prepare करता है; जब तक आप fetch न करें कुछ भी Python में नहीं आता।

दो collection styles मौजूद हैं, और इनके बीच चुनना ही lesson है: rows एक बार में एक लीजिए (fetchone) या सब एक साथ लीजिए (fetchall)।

Theory

Token counter window

Results एक counter window पर इंतज़ार करते हैं, order में, printed tokens की तरह।

fetchone() अगला अकेला token लेता है: इसे फिर call कीजिए, आपको अगला मिलता है: हर call से ढेर छोटा होता है। जब ढेर खाली हो, clerk आपको None थमाता है: कुछ नहीं बचा।

fetchall() बाक़ी पूरा ढेर एक box (एक Python list) में एक motion में समेट लेता है। तुरंत फिर से समेटिए? Box empty वापस आता है: ढेर पहले ही लिया जा चुका था।

Theory

दोनों calls, formally

cur.execute("SELECT ...") के बाद:

  • cur.fetchone() अगली row को एक tuple के रूप में return करता है, या result set ख़त्म होने पर None। हर call cursor को आगे बढ़ाता है।
  • cur.fetchall() बाक़ी सभी rows को tuples की list के रूप में return करता है (कुछ न बचे तो empty list [])।
  • cur.fetchmany(n) एक list के रूप में n तक rows return करता है: बड़े results के लिए middle ground।

Columns position से आते हैं: row[0] आपके SELECT का पहला column है, row[1] दूसरा।

Practical

marks table पर दोनों styles

import sqlite3
conn = sqlite3.connect('college.db')
cur = conn.cursor()

cur.execute("SELECT roll, score FROM marks WHERE subject = 'DBMS'")

# Style 1: one at a time
row = cur.fetchone()
print(row)          # (101, 78)   a TUPLE, even for one row
print(row[1])       # 78          columns by index

# Style 2: everything remaining
rest = cur.fetchall()
print(rest)         # [(102, 55), (103, 91)]  list of tuples
print(len(rest))    # 2

# the pile is now empty:
print(cur.fetchone())   # None
print(cur.fetchall())   # []

# Style 3: the cursor is iterable (fresh execute first!)
cur.execute("SELECT roll, score FROM marks WHERE subject = 'DBMS'")
for roll, score in cur:          # tuple unpacking per row
    print(roll, score)

conn.close()

Think first

चारों prints अंदाज़ा लगाइए

DBMS result set में बिल्कुल 3 rows हैं। execute के बाद, code चलता है:

print(cur.fetchone())

print(len(cur.fetchall()))

print(cur.fetchall())

print(cur.fetchone())

tap करने से पहले चारों outputs अंदाज़ा लगाइए।

Show the answer

1. (101, 78): पहली row, एक tuple के रूप में।

2. 2: fetchall बाक़ी REMAINING rows समेटता है (row 1 पहले ही consumed था)।

3. []: ढेर empty है; एक दूसरा fetchall कुछ नहीं पाता।

4. None: ख़त्म होने पर fetchone।

चारों के पीछे engine: fetch calls एक one-way stream consume करती हैं। जो आपने fetch किया वह बिना fresh execute() के फिर कभी नहीं दिखता।

Quiz

एक program को अकेले top scorer चाहिए: cur.execute('SELECT name FROM ... ORDER BY score DESC LIMIT 1') फिर row = cur.fetchone(); print(row[0])। एक दिन यह crash होता है: TypeError: 'NoneType' object is not subscriptable। क्या हुआ?

  1. Query ने कोई row match नहीं की, fetchone ने None return किया, और None[0] illegal है: indexing से पहले None check कीजिए
  2. fetchone एक string return करता है, और strings को index नहीं किया जा सकता
  3. LIMIT 1 fetchone के साथ incompatible है
  4. Database file किसी और program ने lock कर रखी थी
Show the answer

Query ने कोई row match नहीं की, fetchone ने None return किया, और None[0] illegal है: indexing से पहले None check कीजिए

एक empty result पर (मान लीजिए, marks table में उस दिन कोई rows नहीं थीं), fetchone() None return करता है, और None को index करना बिल्कुल इसी तरह फटता है। Professional pattern: row = cur.fetchone() फिर if row is not None: print(row[0])। Option B उल्टा है (rows tuples हैं, जो index fine होते हैं); LIMIT और fetchone असल में perfectly जोड़ी बनाते हैं; और एक locked file एक अलग, स्पष्ट रूप से नाम वाली error उठाती है।

Watch out

तीन fetch traps

Double fetchall: दूसरी call [] return करती है और beginners एक घंटा 'lost data' bug ढूँढते हैं। एक बार fetch कीजिए, list को एक variable में रखिए।

None को index करना: जब भी एक query empty हो सकती है यह possible है: पहले if row: test कीजिए।

Comma reality भूलना: एक-column row tuple है ('Riya',), bare string नहीं: row[0] से extract कीजिए। Exams print(row) output दिखाते हैं और पूछते हैं brackets और comma क्यों दिखते हैं।

Theory

दोनों के बीच चुनना

fetchall() classroom-sized data के लिए comfortable और सही है: एक list, freely loop कीजिए। fetchone() (या cursor iterate करना) चमकता है जब results बहुत बड़े हों: एक बार में एक row memory में, वही कारण Unit 2 के backups stream करते हैं सब कुछ load करने के बजाय। ResultDesk की report screens fetchall करेंगी; इसका CSV re-import checker iterate करेगा। अगला lesson unit बंद करता है: changes वापस लिखना, और आख़िरकार रखा गया commit() का promise।

Summary

Key takeaways

  • execute() results prepare करता है; जब तक आप fetch न करें कुछ भी Python तक नहीं पहुँचता।
  • fetchone() → अगली row एक tuple के रूप में, या ख़त्म होने पर None; हर call cursor आगे बढ़ाता है।
  • fetchall() → बाक़ी सभी rows tuples की list के रूप में; कुछ न बचे तो []।
  • Fetched rows consumed हैं: दूसरा fetchall [] देता है, कभी repeat नहीं।
  • fetchone results guard कीजिए: अगर row None है, index मत कीजिए।
  • Columns position से आते हैं: row[0], row[1], SELECT के order में; single-column rows अभी भी tuples हैं।
  • Memory hook: counter window पर tokens, एक-एक करके या सब समेटे हुए लिए गए।

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Python interaction with SQLite

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Single row and multi-row fetch (fetchone(), fetchall()) · Database Handling using Python · Gri-Learn