PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Python · Theory

Transactions

← All stacks

Theory

119/268

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.

Exam tip

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

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.

Short notes

  • DefTransactions uses connect + cursor + SQL/API.
  • RuleTransactions — parameterized queries. Never + user text into SQL.
  • RememberTransactions — commit after write. close when done.
  • TrapTransactions — open connections left hanging; passwords in source.

Questions

1

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

2

What does the example print, and why?

3

What mistake do freshers make with Transactions?

Previous← JOINNextMongoDB in Python →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.