Professional Documents
Culture Documents
Crud Ensqlite
Crud Ensqlite
Connect to the Database: To interact with an SQLite database, you first need to
connect to it.
python
import sqlite3
python
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER)''')
conn.commit()
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()
python
# Retrieve data from the table
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
python
# Update data in the table
cursor.execute("UPDATE users SET age = 35 WHERE name = 'Alice'")
conn.commit()
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()