Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views

Handles Database Connection and Operations Like Select, Insert, Update, Delete Using Python

Uploaded by

Himanshu Tonk
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)
1 views

Handles Database Connection and Operations Like Select, Insert, Update, Delete Using Python

Uploaded by

Himanshu Tonk
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/ 5

Handles database connection and operations like select, insert, update,

delete using Python

import mysql.connector as mycon

# Database connection function


def connect_to_database():
try:
connection = mycon.connect(
host='localhost',
user='root',
password='Prince1@#',
database='spartan'
)
print("Connection successful!")
return connection
except mycon.Error as e:
print(f"Error connecting to the database: {e}")
return None

# 1. SELECT operation to fetch all users


def select_all_users():
connection = connect_to_database()
if connection:
try:
cursor = connection.cursor()
cursor.execute("SELECT * FROM users;")
results = cursor.fetchall()
print("Users in the database:")
for row in results:
print(row)
except mycon.Error as e:
print(f"Error fetching users: {e}")
finally:
connection.close()

# 2. INSERT operation to add a new user


def insert_user(name, age):
connection = connect_to_database()
if connection:
try:
cursor = connection.cursor()
cursor.execute("INSERT INTO users (name, age)
VALUES (%s, %s);", (name, age))
connection.commit() # Commit the transaction
print(f"User {name} added successfully.")
except mycon.Error as e:
print(f"Error inserting user: {e}")
finally:
connection.close()

# 3. UPDATE operation to update a user's age


def update_user_age(user_id, new_age):
connection = connect_to_database()
if connection:
try:
cursor = connection.cursor()
cursor.execute("UPDATE users SET age = %s WHERE
id = %s;", (new_age, user_id))
connection.commit() # Commit the transaction
print(f"User with ID {user_id} updated
successfully.")
except mycon.Error as e:
print(f"Error updating user: {e}")
finally:
connection.close()

# 4. DELETE operation to remove a user by ID


def delete_user(user_id):
connection = connect_to_database()
if connection:
try:
cursor = connection.cursor()
cursor.execute("DELETE FROM users WHERE id =
%s;", (user_id,))
connection.commit() # Commit the transaction
print(f"User with ID {user_id} deleted
successfully.")
except mycon.Error as e:
print(f"Error deleting user: {e}")
finally:
connection.close()

# 5. Custom operation to get users older than a specific age


def get_users_older_than(age):
connection = connect_to_database()
if connection:
try:
cursor = connection.cursor()
cursor.execute("SELECT * FROM users WHERE age >
%s;", (age,))
results = cursor.fetchall()
print(f"Users older than {age}:")
for row in results:
print(row)
except mycon.Error as e:
print(f"Error fetching users: {e}")
finally:
connection.close()

# Main function to call all operations


def main():
# Fetch all users
select_all_users()

# Add a new user


insert_user('Prince', 19)

# Update user's age


update_user_age(1, 28) # Assume user with ID 1 exists

# Delete a user
delete_user(2) # Assume user with ID 2 exists

# Get users older than 30


get_users_older_than(30)
if __name__ == "__main__":
main()

Expected Output:

Connection successful!
Users in the database:
(1, 'Prince', 19)
(2, 'Neelesh', 19)
(3, 'Ram', 35)

User Prince added successfully.


User with ID 1 updated successfully.
User with ID 2 deleted successfully.
Users older than 30:
(3, 'Ram', 35)

Explanation of the Code:

1. Database Connection (connect_to_database):


○ This function establishes a connection to the MySQL database
using the mysql.connector library.
○ Replace localhost, root, yourpassword, and yourdatabase
with your actual database details.
2. Database Operations:
○ select_all_users(): Fetches all users from the users table.
○ insert_user(name, age): Inserts a new user into the users
table with the given name and age.
○ update_user_age(user_id, new_age): Updates the age of a
user identified by user_id.
○ delete_user(user_id): Deletes a user by their user_id.
○ get_users_older_than(age): Fetches users who are older than
the specified age.
3. Main Function:
○ The main() function calls each of the database operations in
sequence:
■ It first fetches all users.
■ Then it inserts a new user, updates an existing user's age,
deletes a user, and fetches users older than a certain age.
Thank You

You might also like