DB connection — Python Technical Interview Questions & Answers
DB connection
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.
Technical Interview Tip: Never string-format user text into SQL.
Code Examples for DB connection
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.
How to Explain DB connection to an Interviewer
Explain DB connection as if you are teaching a junior — definition, then one tiny script.
connect → cursor → execute → close. Parameterized SQL.
What does the example print, and why?
DB connection — output: 1
What mistake do freshers make with DB connection?
Passwords in source. Open connections.