Read OperationThe SELECT statement is used to read the values from the databases. We can restrict the output of a select query by using various clause in SQL like where, limit, etc. Python provides the fetchall() method returns the data stored inside the table in the form of rows. We can iterate the result to get the individual rows. In this section of the tutorial, we will extract the data from the database by using the python script. We will also format the output to print it on the console. ExampleOutput: ('John', 101, 25000.0, 201, 'Newyork') ('John', 102, 25000.0, 201, 'Newyork') ('David', 103, 25000.0, 202, 'Port of spain') ('Nick', 104, 90000.0, 201, 'Newyork') ('Mike', 105, 28000.0, 202, 'Guyana') Reading specific columnsWe can read the specific columns by mentioning their names instead of using star (*). In the following example, we will read the name, id, and salary from the Employee table and print it on the console. ExampleOutput: ('John', 101, 25000.0) ('John', 102, 25000.0) ('David', 103, 25000.0) ('Nick', 104, 90000.0) ('Mike', 105, 28000.0) The fetchone() methodThe fetchone() method is used to fetch only one row from the table. The fetchone() method returns the next row of the result-set. Consider the following example. ExampleOutput: ('John', 101, 25000.0) Formatting the resultWe can format the result by iterating over the result produced by the fetchall() or fetchone() method of cursor object since the result exists as the tuple object which is not readable. Consider the following example. ExampleOutput: Name id Salary John 101 25000 John 102 25000 David 103 25000 Nick 104 90000 Mike 105 28000 Using where clauseWe can restrict the result produced by the select statement by using the where clause. This will extract only those columns which satisfy the where condition. Consider the following example. Example: printing the names that start with jOutput: Name id Salary John 101 25000 John 102 25000 Example: printing the names with id = 101, 102, and 103Output: Name id Salary John 101 25000 John 102 25000 David 103 2500 Ordering the resultThe ORDER BY clause is used to order the result. Consider the following example. ExampleOutput: Name id Salary David 103 25000 John 101 25000 John 102 25000 Mike 105 28000 Nick 104 90000 Order by DESCThis orders the result in the decreasing order of a particular column. ExampleOutput: Name id Salary Nick 104 90000 Mike 105 28000 John 101 25000 John 102 25000 David 103 25000 Next TopicUpdate Operation |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India