Using Select Statement in Python to Get data from MySql Database
Select statement is a Sql statement to
get the data from table. Here we write a query as select to get all the data
from database and use FOR loop to display data. We write another query with where
clause to filter data. To Filter data ‘code’ input is taken from screen and
passed as parameter to query and display records with respect to ‘code’.
File insert_emp.py
from database_connection import *
mycursor=db_con.cursor()
query="select code,name from emp"
mycursor.execute(query)
print "All Data"
for (code,name) in mycursor:
print
code,name
# Write code to filter data using WHERE
clause and execute.
query2="select code,name from emp where
code='a01'"
print "filter Data"
mycursor.execute(query2)
for (code,name) in mycursor:
print
code,name
# Write code to filter data by passing
a parameter to WHERE clause on input from screen
pcode=raw_input("Enter code of emp to
see Details: ")
query3="select code,name from emp where
code=%s"
print "filter Data based on Input"
mycursor.execute(query3,(pcode,))
for (code,name) in mycursor:
print
code,name
Result
No comments:
Post a Comment