Created
June 18, 2024 04:51
-
-
Save chandra-prakash-meghwal/20a4d0fd8761f299e7d094180b671acd to your computer and use it in GitHub Desktop.
python mysql fetch rows as generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mysql.connector | |
def fetch_rows_as_generator(query, chunk_size=100): | |
connection = mysql.connector.connect( | |
host='localhost', | |
user='your_username', | |
password='your_password', | |
database='your_database' | |
) | |
cursor = connection.cursor() | |
cursor.execute(query) | |
while True: | |
rows = cursor.fetchmany(chunk_size) | |
if not rows: | |
break | |
for row in rows: | |
yield row | |
cursor.close() | |
connection.close() | |
# Define your query | |
query = "SELECT id, column1, column2 FROM my_table" # Adjust the query as needed | |
# Use the generator to fetch and process rows | |
for row in fetch_rows_as_generator(query): | |
print(row) # Process each row |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment