Jumat, 31 Oktober 2025

Selasa, 28 Oktober 2025

PYHTON - SQLITE - CRUD - MASIH ERROR

 




import sqlite3


# FOR CREATING RECORDS FUNCTION DEFINITION

def create():

    try:

        con = sqlite3.connect("data.db")

        cursor = con.cursor()

        while (True):

            name = input("Enter Name: ")

            age = int(input("Enter Age: "))

            gender = input("Enter Gender: ")

            salary = int(input("Enter Salary: "))

            data = (name, age, gender, salary,)

            query = "INSERT into USERS (name, age, gender, salary) VALUES (?, ?, ?,?)"

            cursor.execute(query, data)

            con.commit()

            ch = input("Do You want to Add More Records(Y/N): ")

            if ch == "N" or ch == "n":

                cursor.close()

                break

            else:

                pass

    except:

        print("Error in Record Creation")


# FOR READING ONE RECORD FUNCTION DEFINITION

def read_one():

    con = sqlite3.connect("data.db")

    cursor = con.cursor()

    ids = int(input("Enter Your ID: "))

    query = "SELECT * from USERS WHERE id = ?"

    result = cursor.execute(query, (ids,))

    if (result):

        for i in result:

            print(f"Name is: {i[1]}")

            print(f"Age is: {i[2]}")

            print(f"Salary is: {i[4]}")

    else:

        print("Roll Number Does not Exist")

        cursor.close()


# FOR READING ALL RECORDS FUNCTION DEFINITION

def read_all():

    con = sqlite3.connect("data.db")

    cursor = con.cursor()

    query = "SELECT * from USERS"

    result = cursor.execute(query)

    if (result):

        print("\n<===Available Records===>")

        for i in result:

            print(f"Name is : {i[1]}")

            print(f"Age is : {i[2]}")

            print(f"Salary is : {i[4]}\n")

    else:

        pass

    

# FOR UPDATING RECORDS FUNCTION DEFINITION

def update():

    con = sqlite3.connect("data.db")

    cursor = con.cursor()

    idd = int(input("Enter ID: "))

    name = input("Enter Name: ")

    age = int(input("Enter Age: "))

    gender = input("Enter Gender: ")

    salary = int(input("Enter Salary: "))

    data = (name, age, gender, salary, idd,)

    query = "UPDATE USERS set name = ?, age = ?, gender = ?, salary = ? WHERE id = ?"

    result = cursor.execute(query, data)

    con.commit()

    cursor.close()

    if (result):

        print("Records Updated")

    else:

        print("Something Error in Updation")


# FOR DELETING RECORDS FUNCTION DEFINITION

def delete():

    con = sqlite3.connect("data.db")

    cursor = con.cursor()

    idd = int(input("Enter ID: "))

    query = "DELETE from USERS where ID = ?"

    result = cursor.execute(query, (idd,))

    con.commit()

    cursor.close()

    if (result):

        print("One record Deleted")

    else:

        print("Something Error in Deletion")


# MAIN BLOCK

try:

    while (True):

        print("1). Create Records: ")

        print("2). Read Records: ")

        print("3). Update Records: ")

        print("4). Delete Records: ")

        print("5). Exit")

        ch = int(input("Enter Your Choice: "))

        if ch == 1:

            create()

        elif ch == 2:

            print("1). Read Single Record")

            print("2). Read All Records")

            choice = int(input("Enter Your Choice: "))

            if choice == 1:

                read_one()

            elif choice == 2:

                read_all()

            else:

                print("Wrong Choice Entered")

        elif ch == 3:

            update()

        elif ch == 4:

            delete()

        elif ch == 5:

            break

        else:

            print("Enter Correct Choice")

except:

    print("Database Error")


#END


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

import sqlite3

# Database Connectivity

try:
    con = sqlite3.connect("data.db")
    cursor = con.cursor()
    print("Connected to Database Successfully")
    #Data Updating Process-(Single Row & Column)
    query = "Update USERS set age = 26 where id = 3"
    cursor.execute(query)
    con.commit()
    cursor.close()
except:
    print("Database Error")
==========================================
import sqlite3

# Database Connectivity
def updation(names,idd):
    try:
        con = sqlite3.connect("data.db")
        cursor = con.cursor()
        print("Connected to Database Successfully")
        #Data Updating Process-(Single Row & Column)
        query = "Update USERS set name = ? where id = ?"
        cursor.execute(query,(names,idd,))
        con.commit()
        cursor.close()
    except:
        print("Database Error")

updation("Newton",3)

import sqlite3

# Database Connectivity
def updation(data):
    try:
        con = sqlite3.connect("data.db")
        cursor = con.cursor()
        print("Connected to Database Successfully")
        #Data Updating Process-(multiple-rows)
        query = "Update USERS set name = ? where id = ?"
        cursor.executemany(query,data)
        con.commit()
        cursor.close()
    except:
        print("Database Error")

data = [("Newton",3), ("Ricky",4)]
updation(data)

import sqlite3

# Database Connectivity
def updation(data):
    try:
        con = sqlite3.connect("data.db")
        cursor = con.cursor()
        print("Connected to Database Successfully")
        #Data Updating Process-(multiple-rows)
        query = "Update USERS set name = ? where id = ?"
        cursor.executemany(query,data)
        con.commit()
        cursor.close()
    except:
        print("Database Error")

data = [("Newton",3), ("Ricky",4)]
updation(data)
import sqlite3

# Database Connectivity

try:
    con = sqlite3.connect("data.db")
    cursor = con.cursor()
    print("Connected to Database Successfully")
    #Data Updating Process-(multiple-columns)
    query = "Update USERS set name = ?, age = ? where id = ?"
    cursor.execute(query,("Jordan",28,4,))
    con.commit()
    cursor.close()
except:
    print("Database Error")
import sqlite3

# Database Connectivity
try:
    con = sqlite3.connect("data.db")
    cursor = con.cursor()
    print("Connected to Database Successfully")
    #Data fetching Process-(One Record)
    query = "SELECT * from USERS"
    x = cursor.execute(query).fetchone()
    print(x)
    #format
    print(f" ID is {x[0]} Age is {x[1]} & Name is {x[2]}")
except:
    print("Database Error")
#Importing Database Library
import sqlite3

# Database Connectivity
try:
    con = sqlite3.connect("data.db")
    cursor = con.cursor()
    print("Connected to Database Successfully")
    #Data fetching Process-(Many Record)
    query = "SELECT * from USERS"
    x = cursor.execute(query).fetchmany(2)
    for i in x:
        print(f" ID is {i[0]} Age is {i[1]} & Name is {i[2]}\n")
except:
    print("Database Error")

#END
import sqlite3

# Database Connectivity
try:
    con = sqlite3.connect("data.db")
    cursor = con.cursor()
    print("Connected to Database Successfully")
    #Data fetching Process-(ALL Records)
    query = "SELECT * from USERS"
    x = cursor.execute(query).fetchall()
    for i in x:
        print(f" ID is {i[0]} Age is {i[1]} & Name is {i[2]}\n")
except:
    print("Database Error")
import sqlite3

# Database Connectivity
try:
    con = sqlite3.connect("data.db")
    cursor = con.cursor()
    print("Connected to Database Successfully")
    #Data Insertion Process
    name = input("Enter Name: ")
    age = int(input("Enter Age: "))
    gender = input("Enter your Gender: ")
    query = "INSERT into USERS(name, age, gender) VALUES (?,?,?)"
    data = (name, age, gender,)
    cursor.execute(query, data)
    con.commit()
    if(cursor.execute(query,data)):
        print("Data Inserted Successfully")
    else:
        print("Data not Inserted")
    cursor.close()
except:
    print("Database Error")
import sqlite3

# Database Connectivity
try:
    con = sqlite3.connect("data.db")
    cursor = con.cursor()
    print("Connected to Database Successfully")
    #Data inserting Process-(Multiple Records)
    while(True):
        name = input("Enter your Name: ")
        age = int(input("Enter your Age: "))
        gender = input("Enter your gender: ")
        data = (name, age, gender,)
        query = "INSERT into USERS(name,age,gender) VALUES (?,?,?)"
        cursor.execute(query,data)
        con.commit()
        ch = input("Do you want to Enter more Records(Y/N): ")
        if ch == "n" or ch == "N":
            break
        else:
            pass
    cursor.close()
except:
    print("Database Error")


import sqlite3

# Database Connectivity
def variables(name,age,gender):
    try:
        con = sqlite3.connect("data.db")
        cursor = con.cursor()
        print("Connected to Database Successfully")
        #Data inserting Process-(Parameterized Query)
        data = (name, age, gender,)
        query = "INSERT into USERS(name,age,gender) VALUES (?,?,?)"
        cursor.execute(query,data)
        con.commit()
        cursor.close()
    except:
        print("Database Error")

variables("Amanda",22,"F")


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()

Senin, 27 Oktober 2025

PYTHON & SQLITE3 & WXPYTHON GUI

 




import wx

import sqlite3


class MyFrame(wx.Frame):

    def __init__(self, parent, title):

        super(MyFrame, self).__init__(parent, title=title, size=(400, 300))


        self.panel = wx.Panel(self)

        self.name_label = wx.StaticText(self.panel, label="Name:")

        self.name_text = wx.TextCtrl(self.panel)

        self.email_label = wx.StaticText(self.panel, label="Email:")

        self.email_text = wx.TextCtrl(self.panel)

        self.add_button = wx.Button(self.panel, label="Add User")

        self.display_button = wx.Button(self.panel, label="Display Users")

        self.output_text = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE | wx.TE_READONLY)


        self.add_button.Bind(wx.EVT_BUTTON, self.on_add_user)

        self.display_button.Bind(wx.EVT_BUTTON, self.on_display_users)


        self.init_db()

        self.setup_layout()


    def init_db(self):

        self.conn = sqlite3.connect('my_wx_app_db.db')

        self.cursor = self.conn.cursor()

        self.cursor.execute('''

            CREATE TABLE IF NOT EXISTS users (

                id INTEGER PRIMARY KEY,

                name TEXT,

                email TEXT

            )

        ''')

        self.conn.commit()


    def setup_layout(self):

        sizer = wx.BoxSizer(wx.VERTICAL)

        input_sizer = wx.GridSizer(2, 2, 5, 5) # Rows, Cols, HGap, VGap


        input_sizer.Add(self.name_label, 0, wx.ALIGN_RIGHT)

        input_sizer.Add(self.name_text, 1, wx.EXPAND)

        input_sizer.Add(self.email_label, 0, wx.ALIGN_RIGHT)

        input_sizer.Add(self.email_text, 1, wx.EXPAND)


        button_sizer = wx.BoxSizer(wx.HORIZONTAL)

        button_sizer.Add(self.add_button, 0, wx.ALL, 5)

        button_sizer.Add(self.display_button, 0, wx.ALL, 5)


        sizer.Add(input_sizer, 0, wx.EXPAND | wx.ALL, 10)

        sizer.Add(button_sizer, 0, wx.ALIGN_CENTER | wx.ALL, 5)

        sizer.Add(self.output_text, 1, wx.EXPAND | wx.ALL, 10)


        self.panel.SetSizer(sizer)

        self.Centre()

        self.Show()


    def on_add_user(self, event):

        name = self.name_text.GetValue()

        email = self.email_text.GetValue()

        if name and email:

            self.cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", (name, email))

            self.conn.commit()

            self.output_text.AppendText(f"User '{name}' added.\n")

            self.name_text.Clear()

            self.email_text.Clear()

        else:

            wx.MessageBox("Please enter both name and email.", "Input Error", wx.OK | wx.ICON_ERROR)


    def on_display_users(self, event):

        self.output_text.Clear()

        self.cursor.execute("SELECT * FROM users")

        rows = self.cursor.fetchall()

        if rows:

            self.output_text.AppendText("Current Users:\n")

            for row in rows:

                self.output_text.AppendText(f"ID: {row[0]}, Name: {row[1]}, Email: {row[2]}\n")

        else:

            self.output_text.AppendText("No users in the database.\n")


    def OnClose(self, event):

        self.conn.close()

        self.Destroy()


if __name__ == '__main__':

    app = wx.App(False)

    frame = MyFrame(None, "Simple SQLite3 wxPython App")

    app.MainLoop()