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

Python · Theory

DB connection

← All stacks

Theory

112/268

DB connection

A database connection is the live link from Python to the database. Flow: connect → cursor → execute SQL → fetch or commit → close. Use ? placeholders (or the driver’s params). Never build SQL with + user text — that is injection. Commit after writes if autocommit is off. Close so connections don’t leak. Don’t put passwords in source.

Same pattern on sqlite3, MySQL driver, others. Viva steps in order. Mention placeholders in the same breath as execute.

DB connection — output — 1. ? placeholders — real parameterized query, not string + id.

Exam tip

Never string-format user text into SQL.

Example

# DB connection
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table users(id integer)")
cur.execute("insert into users values(?)", (1,))
print(cur.execute("select id from users where id=?", (1,)).fetchone()[0])
con.close()

DB connection — output: 1. ? placeholders — real parameterized query, not string + id.

Short notes

  • Defconnect → cursor → execute → close.
  • RuleParameterized SQL.
  • TrapPasswords in source. Open connections.

Questions

1

Explain DB connection 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 DB connection?

Previous← MySQL setupNextCreate database →
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.