Most real-world applications need to store and retrieve data that outlives the program itself. Databases are the standard solution, and Python makes it easy to talk to them. TheDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/marioaje/Python/llms.txt
Use this file to discover all available pages before exploring further.
pymysql library provides a pure-Python MySQL client that follows the Python DB-API 2.0 specification — a standard interface so that the same patterns (connect, cursor, execute, fetch, commit) work across virtually every relational database driver. Once you grasp those five steps you can adapt them to PostgreSQL, SQLite, or any other DB-API-compatible driver with minimal changes.
Installing pymysql
pymysql is not part of the Python standard library, so it must be installed separately. Run the following command in your terminal before running any of the examples below:
The course examples in
Semana 3 were written and tested using pymysql. If you are working in a virtual environment (recommended), activate it before running pip install.The Database Class — Connecting and Creating a Cursor
Wrapping the database connection in a class is a clean pattern: the constructor (__init__) opens the connection and stores both the connection object and the cursor object as instance variables that every method can share.
Semana 3/curso.py
| Parameter | Description |
|---|---|
host | Hostname or IP address of the MySQL server. |
user | MySQL username used to authenticate. |
password | The password associated with that user. |
db | The database (schema) name to select on connection. |
self.connection.cursor() returns a cursor — the object you use to send SQL statements and receive results. One connection can spawn multiple cursors if needed.
SELECT — Fetching All Records
cursor.execute(sql) sends a SQL string to the server. After a SELECT, call cursor.fetchall() to retrieve every matching row as a tuple. A for loop then unpacks each row by numeric index.
Semana 3/curso.py
curso is a tuple whose positions correspond to the columns listed in the SELECT clause — item[0] is id, item[1] is nombre, and so on.
SELECT — Fetching a Single Record by ID
When you only need one row, usecursor.fetchone() instead of cursor.fetchall(). It returns a single tuple (or None if no row matched).
Semana 3/curso.py
INSERT — Creating a New Record
After executing anINSERT statement you must call self.connection.commit() to persist the change. Without it, the row is written only to a temporary transaction buffer and is rolled back when the connection closes.
Semana 3/curso.py
UPDATE — Modifying Existing Records
The class provides two update methods — one that updates only thenombre column and one that updates all editable columns at once.
try/except Error Handling
Every method wraps its database call in atry/except Exception as e block. This pattern has two important effects:
- It prevents the application from crashing silently — the error message is printed to the console so you know what went wrong.
raisere-throws the exception after printing, so the caller can also react to it (e.g., show an error to the user or attempt a retry).
Exception as the catch-all type captures every non-system-exiting exception, including network failures, SQL syntax errors, and authentication problems — all realistic failure modes when working with a remote database.
The Simpler DataBase Class (sc.py)
The course also includes a leaner version of the database class in Semana 3/sc.py. It demonstrates the same connection pattern but with a minimal set of methods and an explicit close() call — a good starting template.
Semana 3/sc.py
close() explicitly releases the connection back to the server. In longer-running applications this is important to avoid exhausting the server’s connection pool.
CRUD Method Summary
The table below maps each method across both classes to its SQL operation and whether acommit() is required.
| Method | Class | SQL Operation | Requires commit() |
|---|---|---|---|
getCurso() | Database | SELECT … FROM curso | No |
getCursoById(id) | Database | SELECT … WHERE id=? | No |
crearCurso(…) | Database | INSERT INTO curso … | Yes |
updateCursoById(id, nombre) | Database | UPDATE curso SET nombre … | Yes |
updateCursoTiempoById(id, tiempo) | Database | UPDATE curso SET tiempo … | Yes |
updateCursoTotalById(id, …) | Database | UPDATE curso SET … (all fields) | Yes |
select_curso(id) | DataBase | SELECT * WHERE id=? | No |
select_all_curso() | DataBase | SELECT * FROM curso | No |
update_curso(id, nombre) | DataBase | UPDATE curso SET nombre … | Yes |
connection.commit() is only needed for write operations — INSERT, UPDATE, and DELETE. SELECT statements are read-only and do not modify the database, so they take effect immediately without a commit. Forgetting commit() after a write is one of the most common bugs when learning database programming: the code appears to succeed (no exception is raised) but the change never actually persists.