Search Data in Table in SQLite3 Database in Python
Search for Data in in SQLite3 Database Table
Searching for a data is an important part of any Database operation for
- Read a particular data
- Update a particular data
- Delete a particular data
Below is the data what we have in our database with table_name as Employee_Data and Id, Name and Salary as column name
Below is a program which will execute select query to look for the data
# program
import sqlite3 as sql
conn = sql.connect("Employee_Details.db") # creating connection with database(created in current directory)
curs = conn.cursor() # creating cursor to database
curs.execute(select query to search data, need to replace)
result = curs.fetchall()
print("result : ", result)
conn.close()
Query to Search data in database
- to select all data from table (* means full row)
Syntax:
"select * from table_name"
or
"SELECT * FROM table_name"
Actual query to be replaced in above program
curs.execute("select * from Employee_Data")
#Output
result : [(101, 'Er M S Dandyan', 28602.08), (102, 'Techno Xpresss', 29602.08), (103, 'Mandeep Singh', 27602.08), (104, 'Mandy', 24602.08), (105, 'Mandeep', 20602.08)]
- to select a particular row (* means full row)
Syntax :
"select * from table_name where column_name =?",(value,)
or
"SELECT * FROM table_name WHERE column_name =?",(value,)
here, above query will look for value in particular column(need to pass at column_name in above query).
Actual query to be replaced in above program
curs.execute("select * from Employee_Data where Name=?",('Mandeep',))
#Output
result : [(105, 'Mandeep', 20602.08)]
- to select a particular data from full table
Syntax :
"select column_name from table_name"
or
"SELECT column_name FROM table_name"
here, above query will only select value for column_name in entire table
Actual query to be replaced in above program
curs.execute("select Id from Employee_Data")
#Output
result : [(101,), (102,), (103,), (104,), (105,)]
- to select a particular data for a particular field
Syntax :
"select column_name_to_read from table_name where column_name =?",(value,)
or
"SELECT column_name_to_read FROM table_name WHERE column_name =?",(value,)
here above query will only look for the value under column_name_to_read for values matches to column name next to where in query.
Actual query to be replaced in above program
curs.execute("select Id from Employee_Data where Name=?",('Mandeep',))
#Output
result : [(105,)]
So with the above combinations of select queries, data can be read in 3 ways.
Comments
Post a Comment