Skip to content

Instantly share code, notes, and snippets.

@chandra-prakash-meghwal
Created June 18, 2024 04:51
Show Gist options
  • Save chandra-prakash-meghwal/20a4d0fd8761f299e7d094180b671acd to your computer and use it in GitHub Desktop.
Save chandra-prakash-meghwal/20a4d0fd8761f299e7d094180b671acd to your computer and use it in GitHub Desktop.
python mysql fetch rows as generator
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