{ "cells": [ { "cell_type": "markdown", "id": "576a79d0-9368-4643-9b8c-60aaeb3d3752", "metadata": {}, "source": [ "# Fetch Records from a Database" ] }, { "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": "9b0c66ef-fea8-47ed-a4d1-87822c5c3688", "metadata": {}, "outputs": [], "source": [ "conn = make_connection('school.ini')\n", "cursor = conn.cursor()" ] }, { "cell_type": "markdown", "id": "a3d36882-d79f-4825-9385-e1e06325b30f", "metadata": {}, "source": [ "### Use `cursor.fetchall()` to **fetch all the rows** from a query." ] }, { "cell_type": "code", "execution_count": null, "id": "59378ef7-95f3-492c-a567-da27082577ee", "metadata": {}, "outputs": [], "source": [ "sql = \"SELECT * FROM class\"\n", "\n", "cursor.execute(sql)\n", "rows = cursor.fetchall()\n", "count = cursor.rowcount\n", "\n", "print(f'Fetched {count} rows.')\n", "print()\n", "\n", "for row in rows:\n", " print(row)" ] }, { "cell_type": "code", "execution_count": null, "id": "0551ffae-248f-456b-a3aa-14e447365dd5", "metadata": {}, "outputs": [], "source": [ "cursor.close()\n", "conn.close()" ] }, { "cell_type": "code", "execution_count": null, "id": "d39700ed-d498-4baa-8013-dbe6aa1b8aff", "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 }