Home » 
        Python » 
        Python Programs
    
    
    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.
    
    Solution
    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.
    
    Algorithm
    
        - 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
try:
    conn=mysql.connect(host='localhost',port=3306,user='root',password='123',db='myschool')
    cmd=conn.cursor()
    
    pat=input("Enter Faculty Name:")
    
    q="select * from faculties where fname like '%{}%'".format(pat)
    cmd.execute(q)
    rows=cmd.fetchall()
    
    for row in rows:
        print(row[1], row[4])
    conn.close()
except Exception as e:
    print("Error:",e)
Output
Enter Faculty Name: John
John 45000
    
    Python database (SQL/MySQL) programs »
    
    
    
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement