Created
January 12, 2023 19:02
-
-
Save Nicolas-albu/9685541fa1f2f339e74979b1549a3290 to your computer and use it in GitHub Desktop.
Manipulando registros com Python e PostgreSQL
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
import psycopg2 | |
class ecommerce_database: | |
def __init__(self, cod_product, val_product): | |
pass | |
def connection_database(self): | |
connection = psycopg2.connect(host='localhost', | |
database='DB_ECOMMERCE', | |
user='postgres', | |
password='postgres') | |
return connection | |
def create(self, cod_product: int, val_product: float): | |
__sql_insert = f"INSERT INTO TBL_PRODUCTS (COD_PRODUCT, VAL_PRODUCT) VALUES ({cod_product}, {val_product})" | |
connection = self.connection_database() | |
cursor = connection.cursor() | |
try: | |
cursor.execute(__sql_insert) | |
connection.commit() | |
except Exception as error: | |
print("Error: ", error) | |
connection.rollback() | |
cursor.close() | |
def read(self) -> list: | |
connection = self.connection_database() | |
cursor = connection.cursor() | |
cursor.execute("SELECT * FROM TBL_PRODUCTS") | |
records = [record for record in cursor.fetchall()] | |
connection.close() | |
return records | |
def update(self, cod_product: int, val_product: float): | |
__sql_update = f"UPDATE TBL_PRODUCTS SET VAL_PRODUCT = {val_product} WHERE COD_PRODUCT = {cod_product}" | |
connection = self.connection_database() | |
cursor = connection.cursor() | |
try: | |
cursor.execute(__sql_update) | |
connection.commit() | |
except Exception as error: | |
print("Error: ", error) | |
connection.rollback() | |
cursor.close() | |
def delete(self, cod_product): | |
if cod_product in self.read(): | |
__sql_delete = f"DELETE FROM TBL_PRODUCTS WHERE COD_PRODUCT = {cod_product}" | |
connection = self.connection_database() | |
cursor = connection.cursor() | |
cursor.execute(__sql_delete) | |
connection.commit() | |
cursor.close() | |
else: | |
print("cod_product not found in TBL_PRODUCTS") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment