Ch 9 teaches how to connect Python programs to MySQL databases using the mysql.connector module — connecting, executing SQL queries, fetching results, and performing CRUD operations programmatically.
Install: pip install mysql-connector-python. Connect: import mysql.connector; conn = mysql.connector.connect(host="localhost", user="root", passwd="password", database="school"). Create cursor: cur = conn.cursor(). Execute: cur.execute("SELECT * FROM students"). Fetch: cur.fetchone() — one row (tuple), cur.fetchmany(5) — five rows (list of tuples), cur.fetchall() — all remaining rows. cur.rowcount — number of rows affected. Always close: cur.close(); conn.close().
Create (INSERT): cur.execute("INSERT INTO students VALUES(%s,%s,%s)", (1,"Alice",95)). Use %s placeholders for parameterised queries — prevents SQL injection! Read (SELECT): cur.execute("SELECT * FROM students WHERE marks>%s", (80,)). Loop: for row in cur.fetchall(): print(row). Update: cur.execute("UPDATE students SET marks=%s WHERE roll=%s", (98,1)). Delete: cur.execute("DELETE FROM students WHERE roll=%s", (5,)). IMPORTANT: conn.commit() after INSERT/UPDATE/DELETE — otherwise changes are not saved. Use try-except for error handling; conn.rollback() if error occurs.
Download: https://ncert.nic.in/textbook/pdf/lecs109.pdf | Complete Book: https://ncert.nic.in/textbook/pdf/lecs1ps.zip
SQL injection: an attacker inserts malicious SQL through user input. Example: if you build query as f"SELECT * FROM users WHERE name='{input}'" and user enters: ' OR 1=1 --, the query becomes SELECT * FROM users WHERE name='' OR 1=1 --' — returning ALL users. Parameterised queries (placeholders %s): the database treats input as DATA, never as SQL code. cur.execute("SELECT * FROM users WHERE name=%s", (input,)) — even if input contains SQL, it's safely escaped. ALWAYS use parameterised queries for user input — this is a fundamental security practice.
Book a Trial + Diagnostic session. Get a personalized Learning Path with clear milestones, tutor match, and a plan recommendation — all within 24 hours.
Book Trial + Diagnostic →