Search a record from the database table using pattern in Python

Here, we will see a Python program to print the details of the user from a database table that matches the inputted pattern.
Submitted by Shivang Yadav, on February 19, 2021

Problem Statement: In this program, we will get the name of the faculty from the user and then search for a pattern that matches the entered data. Print if a record is found.


We will use Python's pymysql library to work with the database. This library provides the programmer the functionality to run MySQL query using Python.


  • Step 1: Connect to database using connect() method in pymysql.
  • Step 2: Get input of faculty name from the user.
  • Step 3: Create a query to fetch records using the name pattern.
  • Step 4: Execute query and fetch the records.
  • Step 5: Print records.

Python Program to search for a record from table using pattern

import pymysql as mysql

    pat=input("Enter Faculty Name:")
    q="select * from faculties where fname like '%{}%'".format(pat)
    for row in rows:
        print(row[1], row[4])

except Exception as e:


Enter Faculty Name: John
John 45000

Python database (SQL/MySQL) programs »

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.