Transactions — Python Technical Interview Questions & Answers

Transactions

Transactions

  • Transactions is about talking to a database from Python. Pattern is always: connect → cursor → execute → fetch or commit → close.
  • For Transactions: use ? placeholders (or the driver’s params). Never build SQL with + user text — that is injection. sqlite3 is in the stdlib for practice; MySQL/Mongo need a driver.
  • Transactions on the board: insert Asha, select her back, print the name. Same idea on MySQL. Close the connection.
  • Transactions — output: committed 1. commit keeps the write; rollback undoes it.

Technical Interview Tip: Steps in order: connect → execute → fetch/commit → close. Mention placeholders.

Code Examples for Transactions

Example

# Transactions
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table t(n integer)")
try:
    cur.execute("insert into t values(1)")
    con.commit()
    print("committed", cur.execute("select n from t").fetchone()[0])
except Exception:
    con.rollback()
    print("rolled back")
con.close()

Transactions — output: committed 1. commit keeps the write; rollback undoes it.

How to Explain Transactions to an Interviewer

Explain Transactions as if you are teaching a junior — definition, then one tiny script.

Transactions uses connect + cursor + SQL/API. Transactions — parameterized queries. Never + user text into SQL.

What does the example print, and why?

Transactions — output: committed 1

What mistake do freshers make with Transactions?

Transactions — commit after write. close when done.