Selasa, 28 Oktober 2025

PYTHON - SQLITE3 - MODULAR PROGRAMMING ->IMPORT PY FILE TO MAIN PROGRAM

 




customer.py

class Customer:


    def __init__(self, first_name, last_name, age, city, country):

        self.first_name = first_name

        self.last_name = last_name

        self.age = age

        self.city = city

        self.country = country

    

    @property

    def email(self):

        return '{}.{}@gmail.com'.format(self.first_name, self.last_name)

    

    @property

    def fullname(self):

        return '{} {}'.format(self.first_name, self.last_name)


    def __repr__(self):

        return "Customer('{}', '{}', '{}', '{}', '{}')".format(

            self.first_name, 

            self.last_name, 

            self.age, 

            self.city, 

            self.country)


=========================================

import sqlite3
from customer import Customer
connection = sqlite3.connect('customer.db')

cursor = connection.cursor()


def create_customer(customer):
    with connection:
        cursor.execute("INSERT INTO customer VALUES (:first, :last, :age, :city, :country)", 
        {'first':customer.first_name, 'last':customer.last_name,
         'age':customer.age, 'city':customer.city, 'country':customer.country})
    

def get_customers(city):
    cursor.execute("SELECT * FROM customer WHERE city=:city", {'city':city})
    return cursor.fetchall()

def update_city(customer, city):
    with connection:
        cursor.execute("""UPDATE customer SET city=:city 
        WHERE first_name=:first AND last_name=:last""",
        {'first':customer.first_name, 'last':customer.last_name, 'city':city})

def delete_customer(customer):
    with connection:
        cursor.execute("DELETE FROM customer WHERE first_name=:first AND last_name=:last",
        {'first':customer.first_name,'last':customer.last_name})

customer_1 = Customer('brad', 'pit', 40, 'perth', 'Australia')
customer_2 = Customer('sara', 'migel', 25, 'perth', 'Australia')

create_customer(customer_1)
create_customer(customer_2)

update_city(customer_1,'sydney')

delete_customer(customer_2)

print(get_customers('perth'))
print(get_customers('sydney'))



print(cursor.fetchall())

connection.commit()

connection.close()

Tidak ada komentar: