informatica:lenguajes_de_programacion:python:python_db_postgresql
Diferencias
Muestra las diferencias entre dos versiones de la página.
| Ambos lados, revisión anteriorRevisión previaPróxima revisión | Revisión previa | ||
| informatica:lenguajes_de_programacion:python:python_db_postgresql [2025/09/18 05:12] – [Leer tabla] admin | informatica:lenguajes_de_programacion:python:python_db_postgresql [2026/04/15 02:03] (actual) – [Leer tabla] admin | ||
|---|---|---|---|
| Línea 49: | Línea 49: | ||
| * [[https:// | * [[https:// | ||
| * [[https:// | * [[https:// | ||
| + | |||
| + | |||
| + | ===== Python : psycopg2 : fetchone : ejemplo simple ===== | ||
| + | |||
| + | <code python> | ||
| + | |||
| + | import psycopg2 | ||
| + | |||
| + | try: | ||
| + | |||
| + | cnx = psycopg2.connect( user="< | ||
| + | password="< | ||
| + | host="< | ||
| + | port="< | ||
| + | database="< | ||
| + | |||
| + | print(" | ||
| + | print(cnx.get_dsn_parameters(), | ||
| + | |||
| + | cur = cnx.cursor() | ||
| + | cur.execute(" | ||
| + | |||
| + | |||
| + | row = cur.fetchone() #<-- FetchOne | ||
| + | while row is not None: | ||
| + | print( row ) | ||
| + | row = cur.fetchone() | ||
| + | | ||
| + | |||
| + | except (Exception, psycopg2.DatabaseError) as error: | ||
| + | |||
| + | print(error) | ||
| + | | ||
| + | </ | ||
| + | |||
| + | ===== Python : psycopg2 : fetchall : ejemplo simple ===== | ||
| + | |||
| + | |||
| + | |||
| + | |||
| + | |||
| ===== Python : psycopg2 : ejecutar : ejemplo simple ===== | ===== Python : psycopg2 : ejecutar : ejemplo simple ===== | ||
| Línea 80: | Línea 121: | ||
| * [[https:// | * [[https:// | ||
| * [[https:// | * [[https:// | ||
| + | |||
| + | auto-commit: | ||
| + | <code sql> | ||
| + | con.autocommit = True | ||
| + | </ | ||
| Store procedure: | Store procedure: | ||
| Línea 106: | Línea 152: | ||
| * [[https:// | * [[https:// | ||
| + | |||
| + | ===== Ejemplos psycopg2 ===== | ||
| + | |||
| + | <code python> | ||
| + | |||
| + | # 1. Instalar librerías | ||
| + | !pip install psycopg2-binary sqlalchemy | ||
| + | |||
| + | # 2. Importar librerías | ||
| + | import psycopg2 | ||
| + | import pandas as pd | ||
| + | from sqlalchemy import create_engine | ||
| + | |||
| + | # 3. Configurar parámetros de conexión | ||
| + | host = ' | ||
| + | dbname = ' | ||
| + | user = ' | ||
| + | password = ' | ||
| + | port = ' | ||
| + | |||
| + | # 4. Crear conexión con SQLAlchemy (recomendado para pandas) | ||
| + | engine = create_engine(f' | ||
| + | |||
| + | # 5. Leer datos con pandas | ||
| + | query = " | ||
| + | df = pd.read_sql(query, | ||
| + | print(df) | ||
| + | |||
| + | </ | ||
| + | |||
| Backups Automáticos: | Backups Automáticos: | ||
| * [[https:// | * [[https:// | ||
informatica/lenguajes_de_programacion/python/python_db_postgresql.1758172378.txt.gz · Última modificación: 2025/09/18 05:12 por admin
