You are on page 1of 2

1.

Connect to the Database: To interact with an SQLite database, you first need to
connect to it.

python
import sqlite3

# Connect to the SQLite database (or create it if it doesn't exist)


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

# Create a cursor object to execute SQL commands


cursor = conn.cursor()

2. Create a Table (Create operation):

python
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER)''')
conn.commit()

3. Insert Data (Create operation):

python
# Insert data into the table
cursor.execute("INSERT INTO users (name, age) VALUES ('Alice', 30)")
cursor.execute("INSERT INTO users (name, age) VALUES ('Bob', 25)")
conn.commit()

4. Retrieve Data (Read operation):

python
# Retrieve data from the table
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)

5. Update Data (Update operation):

python
# Update data in the table
cursor.execute("UPDATE users SET age = 35 WHERE name = 'Alice'")
conn.commit()

6. Delete Data (Delete operation):

python
# Delete data from the table
cursor.execute("DELETE FROM users WHERE name = 'Bob'")
conn.commit()
7. Close the Connection:

python
# Close the cursor and the connection
cursor.close()
conn.close()

Remember to handle exceptions and errors appropriately in a real-world application. This


example provides a basic understanding of how to perform CRUD operations using SQLite
in Python.

You might also like