What Python standard governs database connections?
The Python Database API Specification (DBAPI), usually referred to as PEP 249.
What Python module is used for connecting to SQLite databases?
The built-in sqlite3 module.
What is the first object you must create to interact with a database?
The Connection object.
Example: Establishing a connection to a SQLite file named ‘app.db’
conn = sqlite3.connect('app.db')
What object do you create from the connection to execute SQL queries?
The Cursor object.
Example: Creating a cursor object
cursor = conn.cursor()
How do you execute an SQL command (like CREATE TABLE)?
Use the cursor’s execute() method: cursor.execute("CREATE TABLE users (id, name)")
How do you ensure changes (like INSERT or UPDATE) are permanently saved to the database?
Call the commit() method on the connection object: conn.commit()
How do you run a SELECT query and retrieve one result row?
Use the fetchone() method on the cursor.
How do you run a SELECT query and retrieve all result rows?
Use the fetchall() method on the cursor.
How do you safely close the connection after you are done?
Call the close() method on both the cursor and the connection: cursor.close() and conn.close()
What keyword is often used to ensure connection and cursor objects are closed automatically?
The with keyword (used for context management).
Example: Connection using the with statement
with sqlite3.connect('app.db') as conn:
What common third-party library is often used for connecting to PostgreSQL?
psycopg2
What common third-party library is often used for connecting to MySQL?
mysql-connector-python or PyMySQL
Why should you never use f-strings to insert data into an SQL query?
It exposes the application to SQL Injection attacks.
How should you pass variable data into an SQL query safely?
Use question marks (?) as placeholders in the query string and pass the variables as a tuple to the execute() method.
Example: Safe insertion of a name variable
name = 'Alice'\ncursor.execute("INSERT INTO users VALUES (?, 'password')", (name,))
What is an ORM (Object-Relational Mapper)?
A library (like SQLAlchemy) that allows you to interact with your database using object-oriented code instead of raw SQL.
What happens if you forget to call conn.commit() after an INSERT statement?
The change will not be saved to the database