0% found this document useful (0 votes)
5 views

Python Exp7

The document contains Python code that interacts with a SQLite database to manage user data. It defines functions to create, read, update, and delete users in a 'users' table. The code demonstrates these functions by adding, updating, and deleting user entries, and displaying the current users in the database.

Uploaded by

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

Python Exp7

The document contains Python code that interacts with a SQLite database to manage user data. It defines functions to create, read, update, and delete users in a 'users' table. The code demonstrates these functions by adding, updating, and deleting user entries, and displaying the current users in the database.

Uploaded by

vraveena10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

1.

SOURCE CODE :-
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER NOT NULL
)''')
conn.commit()

def create_user(name, age):


cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', (name, age))
conn.commit()
print(f"User '{name}' added successfully!")

def read_users():
cursor.execute('SELECT * FROM users')
rows = cursor.fetchall()
print("\nUsers in the database:")
for row in rows:
print(row)

def update_user(user_id, new_name, new_age):


cursor.execute('UPDATE users SET name = ?, age = ? WHERE id = ?', (new_name,
new_age, user_id))
conn.commit()
print(f"User with ID {user_id} updated successfully!")

def delete_user(user_id):
cursor.execute('DELETE FROM users WHERE id = ?', (user_id,))
conn.commit()
print(f"User with ID {user_id} deleted successfully!")

create_user('Alice', 30)
create_user('Bob', 25)
create_user('Charlie', 35)
read_users()
update_user(2, 'Bob Updated', 28)
read_users()
delete_user(1)
read_users()
conn.close()
OUTPUT :

You might also like