How To Fetch Data From Database Using User Input In Python

In this tutorial, we will learn how to fetch data from a database using user input in Python. We’ll be connecting to a MySQL database using the popular MySQL Connector/Python package, and later execute an SQL query to fetch the desired data.

Step 1: Sample Database and Table Setup

For this tutorial, we will assume a sample database named testDB with a table named employee. The employee table has the following columns: emp_id, first_name, last_name, age, and city.

Here’s a sample table setup that you could use:

Step 2: Connecting to the Database

Before fetching data, we need to connect to the MySQL database. Here’s how to connect using the MySQL Connector/Python package:

Step 3: Fetching Data

Now that we have a connection to the database, we can fetch data from the employee table using user input. In this example, we’ll filter the data by the employee’s city.

The fetch_data_from_database function takes the user input (city) and fetches all the records where the city matches the input. The data is retrieved using the fetchall() method, and the function returns the results.

Step 4: Accept User Input and Display Fetched Data

Finally, we’ll accept user input and display the fetched data using the following code:

When you run the script and enter a city name, it will display the employee records for the inputted city.

Output:

Enter a city: New York
Employee Records:
John Doe (ID: 1), Age: 30, City: New York

Conclusion

In this tutorial, we learned how to fetch data from a database using user input in Python with the help of MySQL Connector/Python package. You can easily modify and adapt the code to fetch data using any other database or user input.