-
-
Save parzibyte/388f79d38447bf826469f22dac0c9aae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Conexión a PostgreSQL con Python | |
Ejemplo de CRUD evitando inyecciones SQL | |
@author parzibyte | |
Más tutoriales en: | |
parzibyte.me/blog | |
""" | |
import psycopg2 | |
from bd import conexion | |
try: | |
with conexion.cursor() as cursor: | |
consulta = "INSERT INTO mascotas(nombre, edad) VALUES (%s, %s);" | |
# Podemos llamar muchas veces a .execute con datos distintos | |
cursor.execute(consulta, ("Maggie", 3)) | |
cursor.execute(consulta, ("Capuchina", 2)) | |
cursor.execute(consulta, ("Guayaba", 2)) | |
cursor.execute(consulta, ("Panqué", 1)) | |
cursor.execute(consulta, ("Snowball", 1)) | |
conexion.commit() # Si no haces commit, los cambios no se guardan | |
except psycopg2.Error as e: | |
print("Ocurrió un error al insertar: ", e) | |
finally: | |
conexion.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment