{ "cells": [ { "cell_type": "markdown", "id": "d1eece5a-dd1a-47c3-9596-399863ce1b37", "metadata": {}, "source": [ "# Fetch Records from a Database, *cont'd*" ] }, { "cell_type": "code", "execution_count": null, "id": "8c2769b7-ab08-4ad8-af36-6257935e2508", "metadata": {}, "outputs": [], "source": [ "from DATA225utils import make_connection" ] }, { "cell_type": "code", "execution_count": null, "id": "b6ef2857-2e78-497d-8422-4d27ae1b17a5", "metadata": {}, "outputs": [], "source": [ "conn = make_connection('school.ini')\n", "cursor = conn.cursor()" ] }, { "cell_type": "markdown", "id": "cd1ebd70-9eaa-43e0-bddd-f9759315d5c3", "metadata": {}, "source": [ "#### Use `cursor.fetchmany(n)` to **fetch *n* rows** at a time. The last fetch may return fewer than *n* rows, or the empty list `[]`." ] }, { "cell_type": "code", "execution_count": null, "id": "f8dadf35-ae54-4768-b649-8d954f556952", "metadata": {}, "outputs": [], "source": [ "sql = \"SELECT * FROM contact\";\n", "\n", "rows_per_fetch = 4 # Fetch 4 rows at a time.\n", "\n", "cursor.execute(sql);\n", "rows = cursor.fetchmany(rows_per_fetch)\n", "\n", "index = 1\n", "\n", "while rows != []:\n", " for row in rows:\n", " print(f'{index}: {row}')\n", " index += 1\n", "\n", " print(\"-----\")\n", " rows = cursor.fetchmany(rows_per_fetch)" ] }, { "cell_type": "code", "execution_count": null, "id": "d39700ed-d498-4baa-8013-dbe6aa1b8aff", "metadata": {}, "outputs": [], "source": [ "cursor.close()\n", "conn.close()" ] }, { "cell_type": "code", "execution_count": null, "id": "bd846730-c1d1-4f3c-bcd3-368d48be3146", "metadata": {}, "outputs": [], "source": [ "# Copyright (c) 2023 by Ronald Mak" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.13" } }, "nbformat": 4, "nbformat_minor": 5 }