Q:

Search a record from the database table using pattern in Python

belongs to collection: Python Database (SQL/MySQL) Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python program to search for a record using ID in ... >>
<< Python program to delete a record from database us...