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 »





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

© https://www.includehelp.com some rights reserved.