0% found this document useful (0 votes)
18 views2 pages

Crud Ensqlite

To interact with an SQLite database in Python, you first connect to the database and create a cursor object. You can then perform CRUD (create, read, update, delete) operations like creating a table, inserting data into it, retrieving data from it, updating data, and deleting data. It is important to close the cursor and connection once done to release resources.

Uploaded by

jessirivera2802
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views2 pages

Crud Ensqlite

To interact with an SQLite database in Python, you first connect to the database and create a cursor object. You can then perform CRUD (create, read, update, delete) operations like creating a table, inserting data into it, retrieving data from it, updating data, and deleting data. It is important to close the cursor and connection once done to release resources.

Uploaded by

jessirivera2802
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 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