Data Operations with SQLite Database via Python

access_time 10 months ago visibility136 comment 0

SQLite is one of the most commonly used embedded file databases. All the mainstream programming language/framework provides APIs to interact with SQLite database. In my previous article SQLite in .NET Core with Entity Framework Core, code snippet is provided to interact with SQLite via Microsoft Entity Framework. In this article, I'm going to show you how to perform data operations through Python. 

Prerequisites

Package sqlite3 is pre-built with Python distribution thus there is no need to install it.

You can also use other wrapper Python packages listed in PyPi.

Data operations with SQLite database

Establish connection

Import sqlite3 package and then create a database connection:

import sqlite3

conn = sqlite3.connect('example.sqlite')

If the database file doesn't exist, it will be created automatically.

This connection object will be used in the following code snippets. 

Create table

Use CREATE TABLE command to create a table:

conn.execute('''CREATE TABLE Customer (ID int, Name text, Age int)''')

The above SQL statement create a table named Customer.

Check table details

Use system tables to check the tables in the database:

cursor = conn.execute('''select * from sqlite_master''')
print(cursor.fetchall())
cursor.close()
infosqlite_master is a system object that has all the information of all the objects in the database incl. tables, views, etc. 

The above code create a cursor using execute function and then fetch all the records back.

The output looks like the following:

[('table', 'Customer', 'Customer', 2, 'CREATE TABLE Customer (ID int, Name text, Age int)')]

Insert data into table

Use INSERT statement to insert data into the table.

conn.execute("INSERT INTO Customer  VALUES (1,'Customer 1',30)")  

Verify the result using:

print(conn.execute("select * from Customer").fetchall()) 

The output looks like this:

[(1, 'Customer 1', 30)]

Insert multiple records 

You can insert multiple records from Python array into the table:

customers = [(2,'Customer 2',20), (3,'Customer 3', 25)]
conn.executemany('INSERT INTO Customer VALUES (?,?,?)', customers) 
print(conn.execute("select * from Customer").fetchall())

The output now has three records:

>>> print(conn.execute("select * from Customer").fetchall())
[(1, 'Customer 1', 30), (2, 'Customer 2', 20), (3, 'Customer 3', 25)]

Update record

User UPDATE statement to update records:

conn.execute("Update Customer set Name='Customer Two' where ID =2")
print(conn.execute("select * from Customer").fetchall())

Output:

[(1, 'Customer 1', 30), (2, 'Customer Two', 20), (3, 'Customer 3', 25)]

Delete record

Similarly, DELETE command can be used to delete record:

# Delte record
conn.execute("delete from Customer where ID =3")
print(conn.execute("select * from Customer").fetchall())

Output:

[(1, 'Customer 1', 30), (2, 'Customer Two', 20)]

* Record 3 is deleted successfully. 

Drop table if exists

Use DROP TABLE statement to drop it if it exists:

# Drop table if exists 
conn.execute('''DROP TABLE if exists Customer''')

Commit changes

Call commit function to commit changes in the current transaction:

conn.commit()

Close connection

Remember to close cursor and connection:

conn.close()

Full API reference

Refer to the official documentation about all the APIs available to use:

SQLite 3 API References in Python

View SQLite database

You can also use GUI tools like DB Browser for SQLite to view the content of database or run queries:

info Last modified by Administrator 6 months ago copyright This page is subject to Site terms.
Like this article?
Share on

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts

More from Kontext

Pandas DataFrame Plot - Area Chart
visibility 311
thumb_up 0
access_time 10 months ago

This article provides examples about plotting area chart using  pandas.DataFrame.plot  or  pandas.core.groupby.DataFrameGroupBy.plot   function. The data I'm going to use is the same as the other article  Pandas DataFrame Plot - Bar Chart . I'm also using Jupyter ...

visibility 8659
thumb_up 0
access_time 2 years ago

Spark has easy fluent APIs that can be used to read data from JSON file as DataFrame object. 

visibility 35394
thumb_up 2
access_time 3 years ago

SQLite is a self-contained and embedded SQL database engine. In .NET Core, Entity Framework Core provides APIs to work with SQLite. This page provides sample code to create a SQLite database using package Microsoft.EntityFrameworkCore.Sqlite . Create a .NET Core 2.x console application in ...