INTRODUCTION TO PYTHON PROGRAMMING Unit III
UNIT – V
CHAPTER -2
PYTHON SQLite
In the simplest terms, SQLite is a public-domain software package that provides a
relational database management system, or RDBMS. Relational database systems are
used to store user-defined records in large tables. In addition to data storage and
management, a database engine can process complex query commands that combine
data from multiple tables to generate reports and data summaries. Other popular
RDBMS products include Oracle Database, IBM’s DB2, and Microsoft’s SQL Server on the
commercial side, with MySQL and PostgreSQL being popular open source products.
The “Lite” in SQLite does not refer to its capabilities. Rather, SQLite is lightweight when
it comes to setup complexity, administrative overhead, and resource usage. SQLite is
defined by the following features:
Serverless SQLite does not require a separate server process or system to operate. The
SQLite library accesses its storage files directly.
Zero Configuration No server means no setup. Creating an SQLite database instance is
as easy as opening a file.
Cross-Platform The entire database instance resides in a single cross-platform file,
requiring no administration.
Self-Contained A single library contains the entire database system, which integrates
directly into a host application.
Small Runtime Footprint The default build is less than a megabyte of code and requires
only a few megabytes of memory. With some adjustments, both the library size and
memory use can be significantly reduced..
THE SQLITE MODULE
The sqlite module in Python is used to interact with SQLite databases, which are
lightweight, self-contained, serverless databases that are commonly used for local
storage or small-scale applications. SQLite databases are stored as single files on disk
and offer a simple and efficient way to store and retrieve data.
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 1
INTRODUCTION TO PYTHON PROGRAMMING Unit III
Python SQLite3 module is used to integrate the SQLite database with Python. It is a
standardized Python DBI API 2.0 and provides a straightforward and simple-to-use
interface for interacting with SQLite databases. There is no need to install this module
separately as it comes along with Python after the 2.5x version.
To use sqlite3 module, you must first create a connection object that represents the
database and then optionally you can create a cursor object, which will help you in
executing all the SQL statements.
SQLITE METHODS
CONNECT
In Python, the connect method is used to establish a connection to an SQLite database
using the SQLite library. This method allows you to interact with the database, execute
queries, and perform various operations.
If you specify the database file name that already presents on the disk, it will connect to
it. But if your specified SQLite database file doesn't exist, SQLite creates a new database
for you.
# Connect to an existing database or create a new one if it doesn't exist
connection = sqlite3.connect('database_name.db')
CURSOR
cursor is an object that allows you to interact with the database and execute SQL
statements. It acts as a pointer or a handle to the result set of a query. Cursor class is an
instance using which you can invoke methods that execute SQLite statements, fetch
data from the result sets of the queries. You can create Cursor object using the cursor()
method of the Connection object/class.
cursor = conn.cursor()
EXECUTE
the execute() function is used to execute an SQL statement that creates a table named
"users" if it doesn't already exist. Make sure to replace 'my_database.db' with the path
to your SQLite database file.
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 2
INTRODUCTION TO PYTHON PROGRAMMING Unit III
Remember that after executing a statement, you need to commit the changes
using conn.commit() and close the connection with conn.close().
You can also use the execute() function to perform other SQL operations like inserting,
updating, deleting, and selecting data from the database.
cursor.execute(sql_insert, data)
conn.commit()
conn.close()
CLOSE
the close() method is used to close a database connection that was previously opened
using the connect() function. When you're done working with a database, it's a good
practice to close the connection to free up resources and ensure proper handling of the
database file.
conn.commit()
conn.close()
CONNECT TO A DATABASE
To connect an SQLite database, first, we need to import the sqlite3 module. Then, we
create the connection to the SQLite database file using sqlite3. connect() function.
Finally, once we are done, we should close the connection using sqlite3.
connection = sqlite3.connect('database_name.db')
CREATE TABLE
Using the SQLite CREATE TABLE statement you can create a table in a database.
sqlite> CREATE TABLE CRICKETERS (
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age int,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
sqlite>
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 3
INTRODUCTION TO PYTHON PROGRAMMING Unit III
OPERATIONS ON TABLE-
INSERT RECORDS - To insert data in a table
SELECT RECORDS – Select data from database
UPDATE RECORDS – Updates data in a database
DELETE RECORDS – Deletes data from a database
DROP RECORDS – Deletes a Table
STEPS TO EXECUTE PROGRAM IN SQLITE
1. Importing the sqlite3 module:
In Python, you can interact with SQLite databases using the built-in sqlite3 module. This
module provides various methods to import data into an SQLite database.
import sqlite3
2. Connecting to a Database:
To connect to a database in Python, you typically use a library that provides the
necessary functions and methods for interacting with databases. One of the most
commonly used libraries for this purpose is sqlite3 for SQLite databases,
or psycopg2 for PostgreSQL databases, or mysql-connector-python for MySQL
databases, among others.
# Connect to an SQLite database or create if it doesn't exist
connection = sqlite3.connect('mydatabase.db')
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 4
INTRODUCTION TO PYTHON PROGRAMMING Unit III
3. Creating a Table:
The Cursor object contains all the methods to execute quires and fetch data etc. The cursor
method of the connection class returns a cursor object.
Therefore, to create a table in SQLite database using python −
Establish connection with a database using the connect() method.
Create a cursor object by invoking the cursor() method on the above created
connection object.
Now execute the CREATE TABLE statement using the execute() method of the
Cursor class.
cursor = connection.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
username TEXT,
email TEXT
)
''')
connection.commit()
4. Inserting Data:
cursor.execute('''
INSERT INTO users (username, email) VALUES (?, ?)
''', ('john_doe', '[email protected]'))
connection.commit()
5. Querying Data:
The sqlite3. Cursor class provides three methods namely fetchall(), fetchmany() and,
fetchone() where, The fetchall() method retrieves all the rows in the result set of a
query and returns them as list of tuples. fetchone( ) – The fetchone ( ) method returns
the next row of a query result set or None in case there is no row left. cursor.
fetchmany( ) method that returns the next number of rows (n) of the result set.
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 5
INTRODUCTION TO PYTHON PROGRAMMING Unit III
cursor.execute('SELECT * FROM users')
rows = cursor.fetchall()
for row in rows:
print(row)
6. Updating Data:
cursor.execute('UPDATE users SET email = ? WHERE username = ?',
('[email protected]', 'john_doe'))
connection.commit()
7. Deleting Data:
cursor.execute('DELETE FROM users WHERE username = ?', ('john_doe',))
connection.commit()
8. Executing Transactions:
try:
with connection:
cursor.execute('INSERT INTO users (username, email) VALUES (?, ?)',
('jane_doe', '[email protected]'))
except sqlite3.IntegrityError as e:
print("Error:", e)
9. Closing the Connection:
connection.close()
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 6