From f033d3117c0db206664454fff79716498c8e9e20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luiz=20Ot=C3=A1vio?= Date: Sat, 15 Apr 2023 20:57:16 -0300 Subject: [PATCH] SSCursor, SSDictCursor e scroll para conjuntos de dados muito grandes no PyMySQL --- aula206/main.py | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/aula206/main.py b/aula206/main.py index ebe24fb..6011d8a 100644 --- a/aula206/main.py +++ b/aula206/main.py @@ -3,12 +3,14 @@ # Pypy: https://pypi.org/project/pymysql/ # GitHub: https://github.com/PyMySQL/PyMySQL import os +from typing import cast import dotenv import pymysql import pymysql.cursors TABLE_NAME = 'customers' +CURRENT_CURSOR = pymysql.cursors.SSDictCursor dotenv.load_dotenv() @@ -18,7 +20,7 @@ connection = pymysql.connect( password=os.environ['MYSQL_PASSWORD'], database=os.environ['MYSQL_DATABASE'], charset='utf8mb4', - cursorclass=pymysql.cursors.DictCursor, + cursorclass=CURRENT_CURSOR, ) with connection: @@ -142,18 +144,26 @@ with connection: # Editando com UPDATE, WHERE e placeholders no PyMySQL with connection.cursor() as cursor: + cursor = cast(CURRENT_CURSOR, cursor) + sql = ( f'UPDATE {TABLE_NAME} ' 'SET nome=%s, idade=%s ' 'WHERE id=%s' ) - cursor.execute(sql, ('Eleonor', 102, 4)) # type: ignore - cursor.execute(f'SELECT * FROM {TABLE_NAME} ') # type: ignore + cursor.execute(sql, ('Eleonor', 102, 4)) + cursor.execute(f'SELECT * FROM {TABLE_NAME} ') - # for row in cursor.fetchall(): # type: ignore - # _id, name, age = row - # print(_id, name, age) + print('For 1: ') + for row in cursor.fetchall_unbuffered(): + print(row) - for row in cursor.fetchall(): # type: ignore + if row['id'] >= 5: + break + + print() + print('For 2: ') + # cursor.scroll(-1) + for row in cursor.fetchall_unbuffered(): print(row) connection.commit()