{ "cells": [ { "cell_type": "markdown", "id": "abae549c-2d2f-486b-8868-e33495db47ce", "metadata": {}, "source": [ "# Dynamically Generated Query String\n", "\n", "### Since we embed SQL code in our Python programs as a string, we can dynamically generate the strings. This greatly enhances the flexibility of our code." ] }, { "cell_type": "code", "execution_count": null, "id": "8c2769b7-ab08-4ad8-af36-6257935e2508", "metadata": {}, "outputs": [], "source": [ "from DATA225utils import make_connection, dataframe_query" ] }, { "cell_type": "code", "execution_count": null, "id": "ca63fa12-302c-4cbe-8335-038f15a78108", "metadata": {}, "outputs": [], "source": [ "def students_of(conn, first_name, last_name):\n", " \"\"\"\n", " Use the database connection conn to\n", " return the students of the teacher\n", " with the first and last names.\n", " \"\"\"\n", " # Generate the appropriate query string.\n", " sql = ( \"\"\"\n", " SELECT student.first, student.last, subject \n", " FROM student, teacher, class, takes\n", " \"\"\"\n", " f\"WHERE teacher.last = '{last_name}' \" # insert last name\n", " f\"AND teacher.first = '{first_name}' \" # insert first name\n", " \"\"\"\n", " AND teacher_id = teacher.id \n", " AND code = class_code \n", " AND student_id = student.id \n", " ORDER BY subject, student.last\n", " \"\"\"\n", " )\n", " \n", " print(sql)\n", " return dataframe_query(conn, sql)" ] }, { "cell_type": "code", "execution_count": null, "id": "f0b2e68e-fa5c-4c0c-ab1f-6248d33897b0", "metadata": {}, "outputs": [], "source": [ "conn = make_connection('school.ini')" ] }, { "cell_type": "code", "execution_count": null, "id": "02ef0e15-b577-4b45-a7ea-d89e105492e0", "metadata": {}, "outputs": [], "source": [ "first = 'John'\n", "last = 'Lane'" ] }, { "cell_type": "code", "execution_count": null, "id": "fc9f52f9-ba34-41cf-947c-31a584e723a6", "metadata": {}, "outputs": [], "source": [ "print(f'Students of teacher {first} {last}:')\n", "\n", "count, students = students_of(conn, first, last)\n", "\n", "if count > 0:\n", " display(students)\n", "else:\n", " print('No students.')" ] }, { "cell_type": "code", "execution_count": null, "id": "ae113741-af4a-4336-93cb-1ad2709d15b6", "metadata": {}, "outputs": [], "source": [ "conn.close()" ] }, { "cell_type": "code", "execution_count": null, "id": "3aee9c4e-c23e-4c3b-b52c-da06cd144dc2", "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 }