Once connected, a Python program can run any SQL statement. This section creates a table and then inserts, updates and deletes rows, using the safe way of passing values and committing changes so they are saved.
Running statements that change data
cursor.execute(sql, params) runs one statement. Values are passed separately as a tuple, with %s placeholders in the SQL.
cursor.executemany(sql, list_of_tuples) runs the same statement for many rows.
cursor.rowcount tells how many rows the last statement affected; cursor.lastrowid gives the id generated by the last INSERT into an AUTO_INCREMENT column.
conn.commit() makes the changes permanent. mysql.connector does not auto-commit by default, so without commit() the changes are lost when the connection closes.
Why parameterised queries
Building SQL by joining strings with user input, such as "... WHERE name = '" + name + "'", is dangerous: a crafted input such as x' OR '1'='1 changes the meaning of the query. This attack is called SQL injection. With %s placeholders, the driver sends the values separately and they are always treated as data, never as SQL.
Key takeaways
execute(sql, params) with %s placeholders; executemany for batches.
rowcount = rows affected; lastrowid = new auto-increment id.
commit() saves changes; nothing is saved automatically by default.
Parameterised queries prevent SQL injection.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a Python fragment that inserts a new employee whose details are read from the user, safely, and prints the new employee’s id.
Show worked answer
first = input("First name: "), age = int(input("Age: ")), then cur.execute("INSERT INTO employee (first_name, age) VALUES (%s, %s)", (first, age)), conn.commit() and print("New employee id:", cur.lastrowid). The values are passed as a tuple separate from the SQL, so whatever the user types is stored as data and cannot alter the statement; commit() saves the row and lastrowid gives its auto-increment id.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/data-access-using-python/creating-tables-and-changing-data-from-python/ to read this page.