
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Database READ Operation in Python
READ Operation on any database means to fetch some useful information from the database.
Once our database connection is established, you are ready to make a query into this database. You can use either fetchone() method to fetch single record or fetchall() method to fetech multiple values from a database table.
- fetchone() − It fetches the next row of a query result set. A result set is an object that is returned when a cursor object is used to query a table.
- fetchall() − It fetches all the rows in a result set. If some rows have already been extracted from the result set, then it retrieves the remaining rows from the result set.
- rowcount − This is a read-only attribute and returns the number of rows that were affected by an execute() method.
Example
The following procedure queries all the records from EMPLOYEE table having salary more than 1000 −
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() sql = "SELECT * FROM EMPLOYEE \ WHERE INCOME > '%d'" % (1000) try: # Execute the SQL command cursor.execute(sql) # Fetch all the rows in a list of lists. results = cursor.fetchall() for row in results: fname = row[0] lname = row[1] age = row[2] sex = row[3] income = row[4] # Now print fetched result print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \ (fname, lname, age, sex, income ) except: print "Error: unable to fecth data" # disconnect from server db.close()
Output
This will produce the following result −
fname=Mac, lname=Mohan, age=20, sex=M, income=2000
- Related Articles
- Database READ Operation in Perl
- Database INSERT Operation in Python
- Database Update Operation in Python
- Database DELETE Operation in Python
- Database INSERT Operation in Perl
- Database UPDATE Operation in Perl
- Database DELETE Operation in Perl
- Using NULL Values in Perl Database Operation
- Explain read mode operation of files in C language
- Write a program in Python to read sample data from an SQL Database
- Commit & RollBack Operation in Python
- Tuple XOR operation in Python
- Python set operation.
- What is operation of <> in Python?
- Database Connection in Python

Advertisements