← Back to Python Course | Chapter 15: Python & MySQL | Lesson 5 of 12

Python MySQL Select From Table

किसी table से rows को SELECT SQL statement से वापस पढ़ा जाता है -- हमेशा की तरह cursor.execute() से चलाकर, फिर fetchall(), fetchone(), या fetchmany() से Python में retrieve किया जाता है, हर एक अलग situation के लिए उपयुक्त है।
Syntax
python
cursor.execute("SELECT column1, column2 FROM table_name")
rows = cursor.fetchall()

सभी Columns Select करना

cursor.execute("SELECT * FROM customers") के बाद cursor.fetchall(), customers table की हर row के हर column को tuples की एक list के रूप में retrieve करता है, हर row के लिए एक tuple, जिससे आपको Python में table की पूरी contents मिल जाती हैं।

Note: Production code में SELECT * की बजाय specific columns के नाम लेना बेहतर है -- यह इस बारे में ज़्यादा explicit है कि आपका code किस पर depend करता है और network पर अनावश्यक data आने से बचाता है।
Warning: Results असल में retrieve करने के लिए execute() के बाद fetchall() call करना ज़रूरी है -- अकेला execute() सिर्फ server पर query चलाता है, Python को data return नहीं करता।

उदाहरण: Selecting All Columns

python
from unittest.mock import MagicMock

conn = MagicMock()
cursor = conn.cursor()
cursor.execute("SELECT * FROM customers")
cursor.fetchall.return_value = [(1, "John", "Highway 21")]
print(cursor.fetchall())  # every column of every row, as a list of tuples

एक Single Row के लिए fetchone() इस्तेमाल करना

cursor.fetchone(), result set से बस अगली single row लाता है (या अगर और rows नहीं हैं तो None), यह तब एक अच्छा choice है जब आप जानते हों या उम्मीद करते हों कि ठीक एक matching row है, जैसे किसी unique ID से user ढूँढना।

Note: जब आपको सिर्फ पहला या इकलौता result चाहिए, तो fetchall()[0] की बजाय fetchone() इस्तेमाल करें -- यह पूरे result set को transfer और memory में रखने का overhead टालता है।
Warning: जब और rows नहीं बचतीं, तो fetchone() None return करता है, कोई error नहीं -- result को unpack या index करने की कोशिश से पहले हमेशा None चेक करें।

उदाहरण: Using fetchone() for a Single Row

python
from unittest.mock import MagicMock

conn = MagicMock()
cursor = conn.cursor()
cursor.execute("SELECT * FROM customers WHERE id = %s", (1,))
cursor.fetchone.return_value = (1, "John", "Highway 21")
print(cursor.fetchone())  # just the next single row, or None

Cursor पर सीधे Iterate करना

execute() चलने के बाद cursor object खुद iterable होता है -- उस पर सीधे for statement से loop करना अंदर ही अंदर rows को एक-एक करके fetch करता है, जो बड़े result sets के लिए memory-efficient है क्योंकि यह सब कुछ एक साथ list में load करने से बचाता है।

Note: बहुत बड़े result sets process करते समय fetchall() की बजाय सीधे cursor पर iterate करें (for row in cursor:), ताकि पूरा result एक साथ memory में न रखना पड़े।
Warning: एक बार cursor पूरी तरह iterate (या fetchall) हो जाए, तो उससे दोबारा पढ़ने की कोशिश कुछ नहीं देती -- दोबारा query करने के लिए आपको execute() फिर से चलाना होगा।

उदाहरण: Iterating the Cursor Directly

python
from unittest.mock import MagicMock

conn = MagicMock()
cursor = conn.cursor()
cursor.execute("SELECT * FROM customers")
cursor.__iter__.return_value = iter([(1, "John"), (2, "Amy")])
for row in cursor:  # fetches rows one at a time instead of loading them all at once
    print(row)

Results को Dictionaries के रूप में Access करना

cursor argument के रूप में mysql.connector.connect(..., dictionary=True) (या conn.cursor(dictionary=True)) हर fetched row को plain tuple की बजाय column name से keyed एक dict के रूप में देता है, जो positional tuple indexes याद रखने से अक्सर ज़्यादा readable होता है।

Note: जब भी कोई query कई columns को छूती है तो conn.cursor(dictionary=True) इस्तेमाल करें, क्योंकि row["column_name"], call site पर row[3] से कहीं ज़्यादा self-documenting है।
Warning: Dictionary cursors, plain tuple cursors की तुलना में थोड़ा extra performance overhead लाते हैं -- बेहद hot, high-throughput query paths के लिए, plain tuples अब भी बेहतर हो सकते हैं।

उदाहरण: Accessing Results as Dictionaries

python
from unittest.mock import MagicMock

conn = MagicMock()
cursor = conn.cursor(dictionary=True)  # rows come back as dicts keyed by column name
cursor.execute("SELECT * FROM customers")
cursor.fetchall.return_value = [{"id": 1, "name": "John"}]
for row in cursor.fetchall():
    print(row["name"])

Result Rows गिनना

cursor.rowcount, SELECT से results fetch करने के बाद पढ़ा जाए तो, बताता है कि query ने कितनी rows return कीं -- पूरे fetched data को देखे बिना जल्दी check करने के लिए उपयोगी कि कोई matching rows हैं भी या नहीं।

Note: यह मान लेने की बजाय कि query हमेशा कम से कम एक row return करती है, cursor.rowcount (या fetchall() list पर बस len()) check करें।
Warning: SELECT queries के लिए, कुछ MySQL drivers rowcount को सही तरीके से सिर्फ results असल में fetch होने के बाद populate करते हैं, execute() चलते ही नहीं -- हमेशा पहले fetch करें।

उदाहरण: Counting Result Rows

python
from unittest.mock import MagicMock

conn = MagicMock()
cursor = conn.cursor()
cursor.execute("SELECT * FROM customers")
cursor.fetchall.return_value = [(1,), (2,), (3,)]
rows = cursor.fetchall()
cursor.rowcount = len(rows)
print(cursor.rowcount)  # how many rows the query returned
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.