Skip to content
Salman Shah edited this page Mar 20, 2018 · 1 revision

SQLite Usage

  • The given set of commands can get the user to interact with the SQLite Database using the Python Command Line Interface.

Installation

There is no need to install sqlite3 module. It is included in the standard library.

Initial Commands

  • These commands are necessary to be executed before running any SQLite Query.
import sqlite3
db = sqlite3.connect("file::memory:?cache=shared", check_same_thread=False)
cur = db.cursor()

List columns in a Particular Table

  • These commands are to be executed if you want to know the columns in a particular table.
cursor = cur.execute('SELECT * FROM rides;')
names = list(map(lambda x: x[0], cursor.description))
print(names)

This will list the columns that are there in the table rides

Fetch all records in a table

  • These commands are to be executed if you want to fetch all the rows in a particular table.
cursor = cur.execute('SELECT * FROM rides;')
rides = cursor.fetchall()
print(rides)

Note

Alternatively you can also use cursor.fetchone() in case you need to fetch only one record.

Add a new record in the table

  • These set of commands are to be executed when a new row has to be added to a particular table.
cycle = cur.execute("INSERT INTO cycles VALUES(1, 'Hrishi') ;")
db.commit()

Delete a record in the table

  • These set of commands are run to delete a particular row in the table.
mydata = cur.execute("DELETE FROM rides WHERE id=6")
db.commit()