Site icon codemaniacstudio

Explain Select, Insert, update, delete using execute() method to interact with SQLite table.

Explain Select, Insert, update, delete using execute() method to interact with SQLite table.

SOLUTION....

1. SELECT – Retrieve data from a table.

import sqlite3

conn = sqlite3.connect('example.db')
cursor = conn.cursor()

cursor.execute("SELECT * FROM students")  # Retrieve all rows
rows = cursor.fetchall()  # Fetch all results
for row in rows:
    print(row)

conn.close()

2. INSERT – Add new data into a table.

conn = sqlite3.connect('example.db')
cursor = conn.cursor()

cursor.execute("INSERT INTO students (name, age) VALUES (?, ?)", ("Alice", 15))
conn.commit()  # Save changes
conn.close()

3. UPDATE – Modify existing data.

conn = sqlite3.connect('example.db')
cursor = conn.cursor()

cursor.execute("UPDATE students SET age = ? WHERE name = ?", (16, "Alice"))
conn.commit()
conn.close()

4. DELETE – Remove data from a table.

conn = sqlite3.connect('example.db')
cursor = conn.cursor()

cursor.execute("DELETE FROM students WHERE name = ?", ("Alice",))
conn.commit()
conn.close()
Exit mobile version