Python Training · Topic 5

Leer datos desde SQL Server

Extrae una tabla o consulta SQL directamente hacia Python para validarla antes de llevarla a BI.

Read Data From SQL Server

Extract a SQL table or query directly into Python for validation before sending it to BI.

⚠️ Advertencia crítica antes de correr cualquier script

No ejecutes scripts de Python contra archivos oficiales, bases de datos reales, carpetas institucionales, SQL Server, Access, APIs internas o datasets sensibles sin autorización formal.

Python puede transformar miles o millones de filas en segundos. Un cambio mal probado puede sobrescribir archivos, alterar columnas críticas, crear resultados incorrectos, exponer datos sensibles o afectar procesos de BI, auditoría o producción.

Regla obligatoria del training: primero se trabaja con data sintética, luego con una copia controlada, después se valida el resultado, y solo entonces se considera usar datos reales siguiendo permisos, backup, change control, data governance y protocolos de ciberseguridad.

  • Permisos: usa solamente archivos y fuentes donde tengas autorización explícita.
  • Backups: nunca sobrescribas data original sin una copia recuperable.
  • Data governance: respeta privacidad, controles de acceso y clasificación de datos.
  • Producción: nunca conectes scripts a fuentes reales sin revisión, aprobación y plan de reversa.

⚠️ Critical warning before running any script

Do not run Python scripts against official files, real databases, institutional folders, SQL Server, Access, internal APIs, or sensitive datasets without formal authorization.

Python can transform thousands or millions of rows in seconds. A poorly tested change can overwrite files, alter critical columns, create incorrect outputs, expose sensitive data, or affect BI, audit, or production processes.

Mandatory training rule: start with synthetic data, then use a controlled copy, validate the result, and only then consider real data while following permissions, backups, change control, data governance, and cybersecurity protocols.

  • Permissions: use only files and sources where you have explicit authorization.
  • Backups: never overwrite original data without a recoverable copy.
  • Data governance: respect privacy, access controls, and data classification.
  • Production: never connect scripts to real sources without review, approval, and rollback planning.

Objetivo del Topic 5

Extrae una tabla o consulta SQL directamente hacia Python para validarla antes de llevarla a BI.

01 · Crear data
02 · Ejecutar limpieza
03 · Verificar resultado
Idea central: Este topic simula SQL Server con SQLite para practicar sin tocar servidores reales.

Topic 5 Objective

Extract a SQL table or query directly into Python for validation before sending it to BI.

01 · Create data
02 · Run cleanup
03 · Verify result
Core idea: This topic simulates SQL Server with SQLite so you can practice without touching real servers.

Ruta de trabajo

Todo se ejecuta dentro de una carpeta controlada:

Working folder

Everything runs inside a controlled folder:

base_path = Path.home() / "Documents" / "AI Practical Training" / "Python" / "Topic 5"

Qué vamos a aprender

  • Crear data sintética controlada.
  • Leer y transformar datos con pandas.
  • Aplicar una regla de limpieza o validación.
  • Exportar resultados para revisión.
  • Verificar el resultado antes de usar datos reales.

What you will learn

  • Create controlled synthetic data.
  • Read and transform data with pandas.
  • Apply a cleaning or validation rule.
  • Export results for review.
  • Verify the result before using real data.
01

Script 1 — Crear data sintética

Este script prepara datos de práctica para ejecutar el ejercicio sin tocar información real.

Script 1 — Create synthetic data

This script prepares practice data to run the exercise without touching real information.

# Python Topic 5 - Script 1
from pathlib import Path
import pandas as pd
import sqlite3

base_path = Path.home() / "Documents" / "AI Practical Training" / "Python" / "Topic 5"
data_path = base_path / "Data"
data_path.mkdir(parents=True, exist_ok=True)

db_path = data_path / "training_hr.db"

sample = pd.DataFrame({
    "Employee_ID": ["10001", "10002", "10003", "10004"],
    "Department": ["Finance", "HR", "IT", "Operations"],
    "Salary": [65000, 58000, 72000, 61000]
})

with sqlite3.connect(db_path) as conn:
    sample.to_sql("EmployeeMaster", conn, if_exists="replace", index=False)

print("Synthetic database created:", db_path)
02

Script 2 — Ejecutar la acción principal

Este script aplica la lógica central del topic y genera el resultado principal.

Script 2 — Run the main action

This script applies the core topic logic and generates the main result.

# Python Topic 5 - Script 2
from pathlib import Path
import pandas as pd
import sqlite3

base_path = Path.home() / "Documents" / "AI Practical Training" / "Python" / "Topic 5"
db_path = base_path / "Data" / "training_hr.db"
output_file = base_path / "Data" / "sql_extract.xlsx"

query = """
SELECT Employee_ID, Department, Salary
FROM EmployeeMaster
WHERE Salary >= 60000
"""

with sqlite3.connect(db_path) as conn:
    df = pd.read_sql(query, conn)

df.to_excel(output_file, index=False)

print("SQL extract created:", output_file)
print(df)
Nota: este patrón debe probarse siempre con data sintética o copias controladas antes de adaptarlo a fuentes reales.
Note: this pattern should always be tested with synthetic data or controlled copies before adapting it to real sources.
03

Script 3 — Verificar o reportar resultados

Este script confirma el resultado final o genera evidencia para revisión.

Script 3 — Verify or report results

This script confirms the final result or generates evidence for review.

# Python Topic 5 - Script 3
from pathlib import Path
import pandas as pd

base_path = Path.home() / "Documents" / "AI Practical Training" / "Python" / "Topic 5"
output_file = base_path / "Data" / "sql_extract.xlsx"

df = pd.read_excel(output_file)
print("Rows extracted:", len(df))
print(df)

Explicación simple del script

  • Path crea rutas portables en Windows.
  • pandas lee, transforma y exporta la tabla.
  • El Script 1 crea data sintética para practicar sin riesgo.
  • El Script 2 aplica la lógica principal del topic.
  • El Script 3 valida el resultado y deja evidencia.

Simple script explanation

  • Path creates portable Windows paths.
  • pandas reads, transforms, and exports the table.
  • Script 1 creates synthetic data for safe practice.
  • Script 2 applies the main topic logic.
  • Script 3 validates the result and leaves evidence.

Ejemplo esperado

CasoResultado
Synthetic SQLite DBsafe practice
SQL queryExcel extract
Salary filtervalidated rows

Expected example

CaseResult
Synthetic SQLite DBsafe practice
SQL queryExcel extract
Salary filtervalidated rows

Conclusión

Este topic simula SQL Server con SQLite para practicar sin tocar servidores reales.

Lección clave: Python aporta valor cuando convierte pasos repetitivos en procesos claros, auditables y reutilizables.

Conclusion

This topic simulates SQL Server with SQLite so you can practice without touching real servers.

Key lesson: Python adds value when it turns repetitive steps into clear, auditable, reusable processes.