- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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 lname = row age = row sex = row income = row # 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()
This will produce the following result −
fname=Mac, lname=Mohan, age=20, sex=M, income=2000
- 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
- Python set operation.
- Tuple XOR operation in Python
- Commit & RollBack Operation in Python
- Database Connection in Python
- Disconnecting Database in Python