{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "7bdfa5dd-9e86-4047-bee1-9bea236c4c81", "metadata": {}, "outputs": [], "source": [ "from mysql.connector import MySQLConnection, Error" ] }, { "cell_type": "code", "execution_count": null, "id": "bf7e4828-9b68-478e-a1b5-9e7a9734c039", "metadata": {}, "outputs": [], "source": [ "def make_connection():\n", " \"\"\"\n", " Make a connection to the school database.\n", " \"\"\"\n", " try:\n", " conn = MySQLConnection(host='localhost',\n", " database='school',\n", " user='root',\n", " password='seekrit')\n", " \n", " if conn.is_connected():\n", " print('Connected to the MySQL database!')\n", " \n", " return conn\n", " \n", " except Error as e:\n", " print('Connection failed.')\n", " print(e)\n", " \n", " return None" ] }, { "cell_type": "code", "execution_count": null, "id": "b823dde9-9c1c-4246-8add-de1f2b6f85a0", "metadata": {}, "outputs": [], "source": [ "conn = make_connection()\n", "cursor = conn.cursor()" ] }, { "cell_type": "code", "execution_count": null, "id": "f743d22f-6ed0-410f-a015-4a9eb34a3181", "metadata": {}, "outputs": [], "source": [ "sql = \"SELECT * FROM class\"\n", "\n", "cursor.execute(sql)\n", "rows = cursor.fetchall()\n", "\n", "for row in rows:\n", " print(row)" ] }, { "cell_type": "code", "execution_count": null, "id": "ae935db9-29cd-4162-8367-f5f46023eb17", "metadata": {}, "outputs": [], "source": [ "sql = ( \"\"\"\n", " SELECT student.first, student.last, subject \n", " FROM student, teacher, class, takes \n", " WHERE teacher.last = 'Flynn' \n", " AND teacher.first = 'Mabel' \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", "cursor.execute(sql)\n", "rows = cursor.fetchall()\n", "\n", "for row in rows:\n", " print(row)" ] }, { "cell_type": "code", "execution_count": null, "id": "9816ccbb-4410-4768-99da-83fb65a62938", "metadata": {}, "outputs": [], "source": [ "cursor.close()\n", "conn.close()" ] } ], "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.12" } }, "nbformat": 4, "nbformat_minor": 5 }