SELECT rows FROM Table - sqlite3 - Python Examples


Select rows from sqlite3 table

Given a table in sqlite Database, one should be able to select one or more rows of a Database Table.

In this tutorial, we shall learn how to select rows of a table in Sqlite Database, with the help of example programs.

Steps to Select Rows from Table of sqlite Database

To select rows from table of sqlite3 database, follow these steps:

  1. Create a connection object to the sqlite database.
  2. Create a cursor to the connection.
  3. Run sqlite3.execute() method with the SELECT FROM query passed to the method.

Examples

1. Select rows from sqlite3 table

The following program fetches all the rows from the sqlite3 database table, named students.

Python Program

import sqlite3

conn = sqlite3.connect('mysqlite.db')
c = conn.cursor()

c.execute('''SELECT * FROM students;''')

rows = c.fetchall()
 
for row in rows:
	print(row)
			 
#commit the changes to db			
conn.commit()
#close the connection
conn.close()

When you run this program, you will see the rows that are present in the table printed to the console output.

(1.0, 'Glen', 8.0)
(2.0, 'Elliot', 7.0)
(3.0, 'Gene', 7.0)

You can also use modifiers with SELECT FROM query to filter, sort or transform your records when required.

2. Select from sqlite3 table with WHERE clause

In this example, we will use WHERE clause with SELECT FROM query to filter the rows based on a condition.

Python Program

import sqlite3

conn = sqlite3.connect('mysqlite.db')
c = conn.cursor()

c.execute('''SELECT * FROM students WHERE name="Elliot";''')

rows = c.fetchall()
 
for row in rows:
	print(row)
			 
#commit the changes to db			
conn.commit()
#close the connection
conn.close()

Output

(2.0, 'Elliot', 7.0)

Summary

In this tutorial of Python Examples, we learned how to select rows of a table with the help of well detailed examples.