0% found this document useful (0 votes)
17 views

DB Python Unit 3

The document discusses importing and using the sqlite3 module in Python to interact with SQLite databases. It covers connecting to a database, executing SQL statements, and performing CRUD operations using methods like execute(), fetchone(), fetchall(), commit(), and close().

Uploaded by

rudanishaili
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

DB Python Unit 3

The document discusses importing and using the sqlite3 module in Python to interact with SQLite databases. It covers connecting to a database, executing SQL statements, and performing CRUD operations using methods like execute(), fetchone(), fetchall(), commit(), and close().

Uploaded by

rudanishaili
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Unit-3: Python interaction with SQLite

3.1 Module: Concepts of module and Using modules in python


3.1.1 Setting PYTHONPATH, Concepts of Namespace and Scope
3.1.2 Concepts of Packages in python

3.2 Importing sqlite3 module


3.2.1 connect() and execute() methods.
3.2.2 Single row and multi-row fetch ( fetchone(), fetchall())
3.2.3 Select, Insert, update, delete using execute () method.
3.2.4 commit() method.

3.1 Module: Concepts of module and Using modules in python.


Python modules are .py files that contain python code. We can use import command to
import specific modules in python file.
There are 2 types of modules:
Inbuilt: inbuilt modules are those python library files that we can use by importing them.
User defines: user define modules are created by programmer foe specific task.

3.1.1 Setting PYTHONPATH, Concepts of Namespace and Scope

Python path is environment variable. When we wish to execute the codes that we save in
our folder using the python idle, we need to locate folder.

Setting python path on local machine:

Open control panel-> select system and security-> select system ->
select advance setting-> select environment variable from advance tab.
Dr. Mallika Bhatt Page 1
Create new path as PYTHONPATH. Here add SQLite folder path which is available in c:
drive.

Python Namespace and Scope


A namespace is a system that has a unique name for each and every object in Python. An
object might be a variable or a method. Python itself maintains a namespace in the form of a
Python dictionary.

Dr. Mallika Bhatt Page 2


The lifetime / scope of a namespace:
A lifetime of a namespace depends upon the scope of objects, if the scope of an object
ends, the lifetime of that namespace comes to an end. Hence, it is not possible to access
the inner namespace’s objects from an outer namespace.

Example:
# a is in the global namespace
a=5
def some_func():

# b is in the local namespace


b=6
def some_inner_func():

# c is in the nested local namespace


c=7
As shown in the following figure, the same object name can be present in multiple
namespaces as isolation between the same name is maintained by their namespace.

a
b b e
f c
c

Namespce1 Namespace2 Namespace3

Dr. Mallika Bhatt Page 3


Scope of Objects in Python example:
Scope refers to the coding region from which a particular Python object is accessible.
Hence one cannot access any particular object from anywhere from the code, the
accessing has to be allowed by the scope of the object.
Let’s take an example to have a detailed understanding of the same:
# Python program showing
# a scope of object

def some_func():
print("Inside some_func")
def some_inner_func():
var = 10
print("Inside inner function, value of var:",var)
some_inner_func()
print("Try printing var from outer function: ",var)
some_func()

Output:
Inside some_func
Inside inner function, value of var: 10

Traceback (most recent call last):


File "/home/1eb47bb3eac2fa36d6bfe5d349dfcb84.py", line 8, in
some_func()
File "/home/1eb47bb3eac2fa36d6bfe5d349dfcb84.py", line 7, in
some_func
print("Try printing var from outer function: ",var)
NameError: name 'var' is not defined

Dr. Mallika Bhatt Page 4


3.1.2 Concepts of Packages in python
Modules contain methods and other objects. Collection of different modules is orgamized
within a package.
We can access package’s module and object from it.
Syntax:
from <package name>.<module name> import <object name>
Example:
from google.colab import drive
we can import all modules by this way: (*)
from <package name> import *

3.2 Importing sqlite3 module (Working with python)

connect () and execute() methods.

To connect 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.close() function.

Python sqlite3 module will look for the database you specify, if the database is not exist
python will create a new database.

You can check your databases by using .databases command in sqlite3

Example:

Create a python file "connect.py", having the following code:

Example 1 import sqlite3

connection = sqlite3.connect("students.db")

connection.close()
Dr. Mallika Bhatt Page 5
As per the above example python will look for the database file “students.db” on the
current working directory (Since we didn’t specify the absolute path) and connect. If the
database “students.db” not exists, then python will create the “students.db” in the current
working directory.

Example 2

import sqlite3

connection = sqlite3.connect("/sqlite3/students.db")

connection.close()

Similar to the Example 1, but this time we specified the absolute path to the database file.
So python will look inside the /sqlite3 folder for the “students.db” which will be created
if does not exist.

Create Sqlite Table in Python 3

To create sqlite tables, we need to execute SQL commands, to execute SQL commands
we need to add a cursor to our connection. In python sqlite cursor use to execute SQL
commands. A cursor is a temporary work area created in the system memory when a
SQL statement is executed. A cursor contains information on a select statement and the
rows of data accessed by it. This temporary work area is used to store the data retrieved
from the database, and manipulate this data.

import sqlite3

connection = sqlite3.connect("students.db")

cursor = connection.cursor()

connection.close()

Dr. Mallika Bhatt Page 6


Now, we can execute create table statement using the cursor.

import sqlite3

connection = sqlite3.connect("students.db")

cursor = connection.cursor()

cursor.execute("CREATE TABLE student_details(id INTEGER,


name TEXT)")

connection.close()

3.2.2 Single row and multi-row fetch ( fetchone(), fetchall())


fetchone() : it will fetch only one row’s records. Retrieve

fetchall() : it will fetch all row’s records.

fetchmany(size): it will fetch number of records.

Demo: fetchone(), fetchall()

Dr. Mallika Bhatt Page 7


3.2.3 Select, Insert, update, delete using execute () method

Insert Data to Sqlite Table in Python 3

Same way using the python cursor, we can add data to the sqlite database table.

import sqlite3

connection = sqlite3.connect("students.db")

cursor = connection.cursor()

cursor.execute("INSERT INTO student_details(id, name) VALUES(1, 'student 1')")

cursor.execute("INSERT INTO student_details(id, name) VALUES(2, 'student 2')")

Once we insert the data, we need to save changes to the database file using commit()
function, before close the db connection.

import sqlite3

connection = sqlite3.connect("students.db")

cursor = connection.cursor()

cursor.execute("INSERT INTO student_details(id, name) VALUES(1, 'student 1')")

cursor.execute("INSERT INTO student_details(id, name) VALUES(2, 'student 2')")

connection.commit()

connection.close()

Dr. Mallika Bhatt Page 8


Read Data from Sqlite Table

In python 3, we can use for loop to read data from sqlite3 table.

import sqlite3

connection = sqlite3.connect("students.db")

cursor = connection.cursor()

select = "SELECT * FROM student_details"

for i in cursor.execute(select):

print(i)

Above Code will output,

(1, 'student 1')

(2, 'student 2')

Update and delete

We can update a record in table with using update command. In created file we will write
this update query with execute command.

We can delete a record in table with using delete command. In created file we will write
this delete query with execute command.

Dr. Mallika Bhatt Page 9


Output:

Commit(): to make permanent changes to database, it is essential to call commit()


method.

Dr. Mallika Bhatt Page 10

You might also like