Professional Documents
Culture Documents
CRUD
CRUD
Create: This operation is used to add a new record to the database. For example, when you create a new user account on a website, you
are performing a create operation.
Read: This operation is used to retrieve data from the database. For example, when you view your profile information on a website, you are
performing a read operation.
Update: This operation is used to modify existing data in the database. For example, when you update your email address or password on
a website, you are performing an update operation.
Delete: This operation is used to remove data from the database. For example, when you delete a post or comment on a social media
platform, you are performing a delete operation.
These four operations are the basic building blocks of any database-driven application.
class User:
def __init__(self, id, name, age, email):
self.id = id
self.name = name
self.age = age
self.email = email
# Example usage
user1 = create_user('Alice', 25, 'alice@example.com')
print(user1.__dict__) # Output: {'id': 1, 'name': 'Alice', 'age': 25, 'email': 'alice@example.com'}
user3 = get_user(1)
print(user3.__dict__) # Output: {'id': 1, 'name': 'Alice', 'age': 25, 'email': 'alice@example.com'}
delete_user(1)
user5 = get_user(1)
print(user5) # Output: None
https://colab.research.google.com/drive/1trAGnHE83p3EdQwpGc3KmVa7Jgd1CD4-?usp=sharing#printMode=true 1/8
4/10/23, 11:38 AM CRUD Operations in Python - Colaboratory
Note that this is just a simple example and not suitable for production use, as it doesn't handle potential errors or concurrency issues that may
arise in a real-world database. In practice, you would typically use a dedicated database system such as SQLite, MySQL, or PostgreSQL to store
and manage data.
import sqlite3
# Create a new table with columns: id, name, age, and email
conn.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER NOT NULL,
email TEXT NOT NULL)''')
<sqlite3.Cursor at 0x7f60e4491dc0>
get_user(1)
delete_user(2)
get_user(1)
get_user(3)
import sqlite3
https://colab.research.google.com/drive/1trAGnHE83p3EdQwpGc3KmVa7Jgd1CD4-?usp=sharing#printMode=true 2/8
4/10/23, 11:38 AM CRUD Operations in Python - Colaboratory
conn = sqlite3.connect('sample.db')
# Create a new table with columns: id, name, age, and email
conn.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER NOT NULL,
email TEXT NOT NULL)''')
# Example usage
create_user('Alice', 25, 'alice@example.com')
user = get_user(1)
print(user) # Output: (1, 'Alice', 25, 'alice@example.com')
update_user(1, 'Alice Smith', 26, 'alice.smith@example.com')
user = get_user(1)
print(user) # Output: (1, 'Alice Smith', 26, 'alice.smith@example.com')
# delete_user(1)
user = get_user(1)
print(user) # Output: None
import sqlite3
# Create a new table with columns: id, name, age, and email
conn.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER NOT NULL,
email TEXT NOT NULL)''')
https://colab.research.google.com/drive/1trAGnHE83p3EdQwpGc3KmVa7Jgd1CD4-?usp=sharing#printMode=true 3/8
4/10/23, 11:38 AM CRUD Operations in Python - Colaboratory
update_user(1, 'Alice Smith', 26, 'alice.smith@example.com')
user = get_user(1)
print(user) # Output: (1, 'Alice Smith', 26, 'alice.smith@example.com')
delete_user(1)
user = get_user(1)
print(user) # Output: None
None
Note that this is just a simple example and not suitable for production use, as it doesn't handle potential errors or security concerns (such as
SQL injection attacks). It's important to always use proper security practices and handle errors appropriately in real-world applications.
import sqlite3
# Create a new table with columns: id, name, age, and email
conn.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER NOT NULL,
email TEXT NOT NULL)''')
# Example usage
create_user('Alice', 25, 'alice@example.com')
create_user('Bob', 30, 'bob@example.com')
user1 = get_user(1)
print(user1) # Output: (1, 'Alice', 25, 'alice@example.com')
update_user(2, 'Bob Smith', 31, 'bob.smith@example.com')
user2 = get_user(2)
print(user2) # Output: (2, 'Bob Smith', 31, 'bob.smith@example.com')
delete_user(1)
user3 = get_user(1)
print(user3) # Output: None
https://colab.research.google.com/drive/1trAGnHE83p3EdQwpGc3KmVa7Jgd1CD4-?usp=sharing#printMode=true 4/8
4/10/23, 11:38 AM CRUD Operations in Python - Colaboratory
None
Here's an example of a Python CRUD code that uses a MySQL database and follows best practices for production use:
import sqlite3
def get_users():
# Retrieve all users from the database
cursor.execute('SELECT * FROM users')
users = cursor.fetchall()
return [{'id': user[0], 'name': user[1], 'age': user[2], 'email': user[3]} for user in users]
def get_user(user_id):
# Retrieve a specific user from the database
cursor.execute('SELECT * FROM users WHERE id = ?', (user_id,))
user = cursor.fetchone()
if not user:
return {'error': 'User not found'}
return {'id': user[0], 'name': user[1], 'age': user[2], 'email': user[3]}
def delete_user(user_id):
# Delete a user from the database
cursor.execute('SELECT * FROM users WHERE id = ?', (user_id,))
user = cursor.fetchone()
if not user:
return {'error': 'User not found'}
cursor.execute('DELETE FROM users WHERE id = ?', (user_id,))
conn.commit()
return {'message': 'User deleted successfully'}
https://colab.research.google.com/drive/1trAGnHE83p3EdQwpGc3KmVa7Jgd1CD4-?usp=sharing#printMode=true 5/8
4/10/23, 11:38 AM CRUD Operations in Python - Colaboratory
create_user('Mantaring', 30, 'mantaring@gmail.com')
get_users()
[{'id': 1,
'name': 'Alice Smith',
'age': 26,
'email': 'alice.smith@example.com'},
{'id': 2, 'name': 'Jonathan', 'age': 49, 'email': 'jvtaylar@gmail.com'},
{'id': 3, 'name': 'Mantaring', 'age': 30, 'email': 'mantaring@gmail.com'},
{'id': 4, 'name': 'John', 'age': 30, 'email': 'john@gmail.com'}]
get_users()
delete_user(1)
import sqlite3
class User:
def __init__(self, name, age, email, user_id=None):
self.name = name
self.age = age
self.email = email
self.user_id = user_id
class UserDB:
def __init__(self, db_name):
self.conn = sqlite3.connect(db_name)
self.cursor = self.conn.cursor()
self.cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER NOT NULL,
email TEXT NOT NULL UNIQUE)''')
self.conn.commit()
def get_users(self):
self.cursor.execute('SELECT * FROM users')
users = self.cursor.fetchall()
return [User(user[1], user[2], user[3], user[0]) for user in users]
https://colab.research.google.com/drive/1trAGnHE83p3EdQwpGc3KmVa7Jgd1CD4-?usp=sharing#printMode=true 6/8
4/10/23, 11:38 AM CRUD Operations in Python - Colaboratory
user = self.cursor.fetchone()
if not user:
return {'error': 'User not found'}
return User(user[1], user[2], user[3], user[0])
f = UserDB('db.db')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-46-839b9045c815> in <cell line: 1>()
----> 1 f = UserDB('db.db')
f.create_user(u)
<__main__.User at 0x7f85b0257f40>
In this example, we have two classes - User and UserDB . The User class is a simple data class that represents a user with properties like
name , age , email , and user ID .
The UserDB class is responsible for interacting with the database and providing functions for creating , reading , updating , and deleting
users from the database.
To use this class, you would need to create an instance of the UserDB class and call the methods as needed. For example:
db = UserDB('db.db')
new_user = User('John Doe', 30, 'johndoe@example.com')
created_user = db.create_user(new_user)
print(created_user.user_id) # prints the ID of the newly created user
created_user = db.create_user(new_user)
print(created_user.user_id) # prints the ID of the newly created user
https://colab.research.google.com/drive/1trAGnHE83p3EdQwpGc3KmVa7Jgd1CD4-?usp=sharing#printMode=true 7/8
4/10/23, 11:38 AM CRUD Operations in Python - Colaboratory
https://colab.research.google.com/drive/1trAGnHE83p3EdQwpGc3KmVa7Jgd1CD4-?usp=sharing#printMode=true 8/8