Query Employees from Specific Department

  • Share this:

Code introduction


This function queries employee information from the database for a specified department.


Technology Stack : mysql-connector-python

Code Type : Database query

Code Difficulty : Intermediate


                
                    
def select_random_employee_from_department(department_id):
    import mysql.connector
    from mysql.connector import Error

    try:
        connection = mysql.connector.connect(
            host='your_host',
            database='your_database',
            user='your_user',
            password='your_password'
        )
        if connection.is_connected():
            cursor = connection.cursor()
            query = "SELECT * FROM employees WHERE department_id = %s"
            cursor.execute(query, (department_id,))
            result = cursor.fetchall()
            return result
    except Error as e:
        print("Error while connecting to MySQL", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()