How to work with the SQLite3 library in Python for interacting with SQLite databases

Daily Dose of Python
2 min readJan 23, 2023

--

Python is a powerful and versatile programming language that is widely used in various industries. In this blog post, we’ll take a look at how to work with the SQLite3 library in Python for interacting with SQLite databases.

SQLite is a lightweight, file-based relational database management system that is widely used in various applications such as mobile apps, web apps, and desktop apps. SQLite3 is the python library which provides an interface to interact with SQLite databases. It is built on top of the C programming language and is included with the python standard library.

The first step in working with SQLite3 is to import it into your code. Once you’ve imported the library, you can create a connection to a SQLite database using the connect() function. For example:

import sqlite3

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

Once you have a connection, you can use it to execute SQL commands. For example, you can use the execute() method to create a table:

conn.execute('''CREATE TABLE COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')

You can also use the execute() method to insert data into a table:

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (1, 'Paul', 32, 'California', 20000.00 )")

You can use the commit() method to save changes to the database:

conn.commit()

You can use the execute() method to fetch data from a table:

cursor = conn.execute("SELECT id, name, address, salary from COMPANY")

In conclusion, the SQLite3 library in Python provides a wide range of tools for interacting with SQLite databases. The connect() function can be used to create a connection to a SQLite database, the execute() method can be used to execute SQL commands,

--

--

Daily Dose of Python

Come and learn something new and exciting about Python every single day! New Post every Day @ 7 PM IST.