How do you execute a query in a database using python? (AI) Flashcards

(40 cards)

1
Q

What object do you need to execute SQL commands?

A

The Cursor object. You create it from your connection: cursor = conn.cursor()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the primary method used to run an SQL string?

A

The execute() method on the cursor object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Example: Executing a simple SELECT query

A
sql_query = "SELECT * FROM users"`\n`cursor.execute(sql_query)`
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you safely pass Python variables into your SQL query?

A

Use placeholders in the SQL string and pass the variables as a second argument (usually a tuple) to execute().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What placeholder is used by sqlite3?

A

The question mark (?). SELECT * FROM users WHERE name = ?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What placeholder is common in libraries like psycopg2 (PostgreSQL) and mysql-connector?

A

The %s placeholder. SELECT * FROM users WHERE name = %s

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Example: Safe execution with a variable (sqlite3)

A

user_name = "Alice"\ncursor.execute("SELECT * FROM users WHERE name = ?", (user_name,))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Why should you never use f-strings or string formatting (like +) to build queries?

A

It creates a major security vulnerability called SQL Injection.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

After executing a SELECT query, how do you retrieve a single row?

A

row = cursor.fetchone()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

After executing a SELECT query, how do you retrieve all matching rows?

A

rows = cursor.fetchall() (This returns a list of tuples)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

After executing a SELECT query, how do you retrieve a specific number of rows?

A

rows = cursor.fetchmany(5) (Fetches 5 rows at a time)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What must you call on the connection object to finalize changes like INSERT, UPDATE, or DELETE?

A

You must call conn.commit().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Example: Executing an INSERT statement

A

cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Bob", "bob@example.com"))\nconn.commit()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What happens if you forget to call conn.commit() after an INSERT?

A

The data will not be saved to the database. The transaction will be rolled back.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What method can you call to undo changes made since the last commit?

A

conn.rollback()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What should you do with the cursor after you are finished with it?

A

Close it to free up resources: cursor.close()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the executemany() method used for?

A

To efficiently run the same SQL command multiple times with different sets of data (e.g., bulk inserting many rows from a list).

18
Q

Example: Using executemany()

A

users_to_add = [("Charlie", "c@ex.com"), ("David", "d@ex.com")]\ncursor.executemany("INSERT INTO users (name, email) VALUES (?, ?)", users_to_add)\nconn.commit()

19
Q

What does cursor.rowcount tell you?

A

The number of rows affected by the last DML command (INSERT, UPDATE, DELETE) or the number of rows returned by a query (behavior can vary by driver).

20
Q

What is the with statement used for in this context?

A

It acts as a context manager, typically for the connection, to automatically commit() on success or rollback() on error, and often ensures the connection is closed.

21
Q

Example: Using with for a connection (recommended)

A

with sqlite3.connect('app.db') as conn:\n cursor = conn.cursor()\n cursor.execute(...)\n # No conn.commit() needed here if used as context manager

22
Q

ORM example

A
from sqlalchemy import create_engine, select
from sqlalchemy.orm import sessionmaker
from models import User

Create engine and session
engine = create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=engine)
session = Session()

Execute query
bob = session.query(User).filter_by(name='Bob').first()
23
Q

What does ORM stand for?

A

Object-Relational Mapper

24
Q

What is the primary goal of an ORM?

A

To map Python classes/objects to database tables/rows, allowing interaction without writing raw SQL.

25
What is the most widely used ORM library in Python?
**SQLAlchemy**
26
In SQLAlchemy, what component manages the database connection and dialect?
The **Engine** (created using `create_engine()`).
27
Example: Creating a database Engine for SQLite
`engine = create_engine('sqlite:///database.db')`
28
What component provides the interface for transactional operations (queries, commits, rollbacks)?
The **Session** (often managed using `SessionMaker`).
29
How do you start a standard query in SQLAlchemy to retrieve data?
By accessing the model class via the session, e.g., `session.query(User)`
30
SQLAlchemy: How do you select **all** records from the User model?
`users = session.query(User).all()`
31
SQLAlchemy: How do you apply a filtering condition (e.g., age > 30)?
Use the **`.filter()`** method, e.g., `session.query(User).filter(User.age > 30)`
32
SQLAlchemy: How do you retrieve only the **first** matching record?
Use the **`.first()`** method.
33
SQLAlchemy: How do you add a new record to the session?
Instantiate the Model class, then use **`session.add(new_object)`**
34
SQLAlchemy: What method finalizes a change (INSERT, UPDATE, DELETE) in the database?
Call **`session.commit()`**
35
SQLAlchemy: How do you update an existing record's email address?
Retrieve the object, modify its attribute (`user.email = 'new@ex.com'`), then call **`session.commit()`**
36
SQLAlchemy: How do you delete a record?
Retrieve the object, then call **`session.delete(object)`**, followed by **`session.commit()`**
37
What Python keyword is recommended to ensure a Session is properly closed?
The **`with`** keyword, as the Session often acts as a context manager.
38
What does the ORM handle automatically that prevents SQL injection attacks?
The **safe parameter binding** (it substitutes variables for you).
39
SQLAlchemy: How do you retrieve a single record by its primary key (ID)? (Older Method)
`session.get(User, user_id)`
40
SQLAlchemy: How do you undo changes made since the last commit or start of the transaction?
Call **`session.rollback()`**