You are on page 1of 8

4/10/23, 11:38 AM CRUD Operations in Python - Colaboratory

CRUD Operations in Python


CRUD is an acronym that stands for Create, Read, Update, and Delete. It refers to the four basic operations that can be performed on persistent
data in a software system.

Here is a brief explanation of each operation:

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

users = {} # simulate a database using a dictionary

# CREATE - Add a new user record to the database


def create_user(name, age, email):
# generate a new id
id = len(users) + 1
user = User(id, name, age, email)
users[id] = user
return user

# READ - Retrieve a user record from the database by id


def get_user(id):
return users.get(id)

# UPDATE - Update an existing user record in the database


def update_user(id, name, age, email):
user = users.get(id)
if user:
user.name = name
user.age = age
user.email = email
return user

# DELETE - Remove a user record from the database by id


def delete_user(id):
return users.pop(id, None)

# Example usage
user1 = create_user('Alice', 25, 'alice@example.com')
print(user1.__dict__) # Output: {'id': 1, 'name': 'Alice', 'age': 25, 'email': 'alice@example.com'}

user2 = create_user('Bob', 30, 'bob@example.com')


print(user2.__dict__) # Output: {'id': 2, 'name': 'Bob', 'age': 30, 'email': 'bob@example.com'}

user3 = get_user(1)
print(user3.__dict__) # Output: {'id': 1, 'name': 'Alice', 'age': 25, 'email': 'alice@example.com'}

update_user(2, 'Bob Smith', 31, 'bob.smith@example.com')


user4 = get_user(2)
print(user4.__dict__) # Output: {'id': 2, 'name': 'Bob Smith', 'age': 31, 'email': 'bob.smith@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

{'id': 1, 'name': 'Alice', 'age': 25, 'email': 'alice@example.com'}


{'id': 2, 'name': 'Bob', 'age': 30, 'email': 'bob@example.com'}
{'id': 1, 'name': 'Alice', 'age': 25, 'email': 'alice@example.com'}
{'id': 2, 'name': 'Bob Smith', 'age': 31, 'email': 'bob.smith@example.com'}
None

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 database or connect to an existing one


conn = sqlite3.connect('example.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)''')

<sqlite3.Cursor at 0x7f60e4491dc0>

# CREATE - Insert a new user record


def create_user(name, age, email):
conn.execute(f"INSERT INTO users (name, age, email) VALUES ('{name}', {age}, '{email}')")
conn.commit()

create_user('Urbano', 25, 'urbano@gmail.com')


create_user('Vallejos', 19, 'vallejos@gmail.com')
create_user('Santos', 20, 'santos@gmail.com')

# READ - Retrieve a user record by id


def get_user(id):
cursor = conn.execute(f"SELECT id, name, age, email FROM users WHERE id={id}")
user = cursor.fetchone()
return user

get_user(1)

(1, 'Urbano', 25, 'urbano@gmail.com')

# UPDATE - Update an existing user record


def update_user(id, name, age, email):
conn.execute(f"UPDATE users SET name='{name}', age={age}, email='{email}' WHERE id={id}")
conn.commit()

update_user(1, 'Urvan', 20, 'pogi@yahoo.com')


get_user(1)

(1, 'Urvan', 20, 'pogi@yahoo.com')

# DELETE - Remove a user record by id


def delete_user(id):
conn.execute(f"DELETE FROM users WHERE id={id}")
conn.commit()

delete_user(2)

get_user(1)
get_user(3)

(3, 'Santos', 20, 'santos@gmail.com')

import sqlite3

# Create a new database or connect to an existing one

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)''')

# CREATE - Insert a new user record


def create_user(name, age, email):
conn.execute(f"INSERT INTO users (name, age, email) VALUES ('{name}', {age}, '{email}')")
conn.commit()

# READ - Retrieve a user record by id


def get_user(id):
cursor = conn.execute(f"SELECT id, name, age, email FROM users WHERE id={id}")
user = cursor.fetchone()
return user

# UPDATE - Update an existing user record


def update_user(id, name, age, email):
conn.execute(f"UPDATE users SET name='{name}', age={age}, email='{email}' WHERE id={id}")
conn.commit()

# DELETE - Remove a user record by id


def delete_user(id):
conn.execute(f"DELETE FROM users WHERE id={id}")
conn.commit()

# 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

# Close the database connection when done


conn.close()

(1, 'Alice', 25, 'alice@example.com')


(1, 'Alice Smith', 26, 'alice.smith@example.com')
(1, 'Alice Smith', 26, 'alice.smith@example.com')

import sqlite3

# Create a new database or connect to an existing one


conn = sqlite3.connect('example.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)''')

# CREATE - Insert a new user record


def create_user(name, age, email):
conn.execute(f"INSERT INTO users (name, age, email) VALUES ('{name}', {age}, '{email}')")
conn.commit()
# Example usage
create_user('Alice', 25, 'alice@example.com')
user = get_user(1)
print(user) # Output: (1, 'Alice', 25, 'alice@example.com')

(1, 'Alice', 25, 'alice@example.com')

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')

(1, 'Alice Smith', 26, 'alice.smith@example.com')

delete_user(1)
user = get_user(1)
print(user) # Output: None

# Close the database connection when done


conn.close()

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

# Connect to the database


conn = sqlite3.connect('users.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)''')

# CREATE - Add a new user record to the database


def create_user(name, age, email):
cursor = conn.cursor()
cursor.execute("INSERT INTO users (name, age, email) VALUES (?, ?, ?)", (name, age, email))
conn.commit()
return cursor.lastrowid

# READ - Retrieve a user record from the database by id


def get_user(id):
cursor = conn.cursor()
cursor.execute("SELECT id, name, age, email FROM users WHERE id=?", (id,))
return cursor.fetchone()

# UPDATE - Update an existing user record in the database


def update_user(id, name, age, email):
cursor = conn.cursor()
cursor.execute("UPDATE users SET name=?, age=?, email=? WHERE id=?", (name, age, email, id))
conn.commit()

# DELETE - Remove a user record from the database by id


def delete_user(id):
cursor = conn.cursor()
cursor.execute("DELETE FROM users WHERE id=?", (id,))
conn.commit()

# 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

# Close the database connection when done


conn.close()

(1, 'Alice', 25, 'alice@example.com')


(2, 'Bob Smith', 31, 'bob.smith@example.com')

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

# Create the database and the users table


conn = sqlite3.connect('sample.db')
cursor = conn.cursor()
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)''')
conn.commit()

def create_user(name, age, email):


# Insert a new user into the database
try:
cursor.execute('''INSERT INTO users(name, age, email)
VALUES(?, ?, ?)''', (name, age, email))
conn.commit()
user_id = cursor.lastrowid
return {'id': user_id, 'name': name, 'age': age, 'email': email}
except sqlite3.IntegrityError:
return {'error': 'Email address already in use'}

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 update_user(user_id, name, age, email):


# Update an existing user in the database
cursor.execute('SELECT * FROM users WHERE id = ?', (user_id,))
user = cursor.fetchone()
if not user:
return {'error': 'User not found'}
try:
cursor.execute('''UPDATE users
SET name = ?, age = ?, email = ?
WHERE id = ?''', (name, age, email, user_id))
conn.commit()
return {'id': user_id, 'name': name, 'age': age, 'email': email}
except sqlite3.IntegrityError:
return {'error': 'Email address already in use'}

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'}

create_user('Jonathan', 49, 'jvtaylar@gmail.com')

{'id': 2, 'name': 'Jonathan', 'age': 49, 'email': 'jvtaylar@gmail.com'}

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')

{'id': 3, 'name': 'Mantaring', 'age': 30, 'email': 'mantaring@gmail.com'}

create_user('John', 30, 'john@gmail.com')

{'id': 4, 'name': 'John', 'age': 30, 'email': 'john@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'}]

update_user(5, 'Joan', 50, 'email@.email.com')

{'error': 'User not found'}

get_users()

[{'id': 1, 'name': 'Joan', 'age': 50, 'email': 'email@.email.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'}]

delete_user(1)

{'message': 'User deleted successfully'}

Here is an example of CRUD using OOP approach

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 create_user(self, user):


try:
self.cursor.execute('''INSERT INTO users(name, age, email)
VALUES(?, ?, ?)''', (user.name, user.age, user.email))
self.conn.commit()
user_id = self.cursor.lastrowid
user.user_id = user_id
return user
except sqlite3.IntegrityError:
return {'error': 'Email address already in use'}

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]

def get_user(self, user_id):


self.cursor.execute('SELECT * FROM users WHERE id = ?', (user_id,))

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])

def update_user(self, user):


self.cursor.execute('SELECT * FROM users WHERE id = ?', (user.user_id,))
old_user = self.cursor.fetchone()
if not old_user:
return {'error': 'User not found'}
try:
self.cursor.execute('''UPDATE users
SET name = ?, age = ?, email = ?
WHERE id = ?''', (user.name, user.age, user.email, user.user_id))
self.conn.commit()
return user
except sqlite3.IntegrityError:
return {'error': 'Email address already in use'}

def delete_user(self, user_id):


self.cursor.execute('SELECT * FROM users WHERE id = ?', (user_id,))
user = self.cursor.fetchone()
if not user:
return {'error': 'User not found'}
self.cursor.execute('DELETE FROM users WHERE id = ?', (user_id,))
self.conn.commit()
return {'message': 'User deleted successfully'}

f = UserDB('db.db')

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-46-839b9045c815> in <cell line: 1>()
----> 1 f = UserDB('db.db')

NameError: name 'UserDB' is not defined

SEARCH STACK OVERFLOW

u = User('Maria', 18, 'maria@email.com')

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

new_user = User('Girl Doe', 25, 'girl@example.com')

created_user = db.create_user(new_user)
print(created_user.user_id) # prints the ID of the newly created user

print(created_user.name, created_user.age, created_user.email, created_user.user_id)

Girl Doe 25 girl@example.com 2

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

You might also like