SlideShare a Scribd company logo
6
Most read
10
Most read
12
Most read
Unit-4
Python SQLite
What is sqlite3 module in Python?
SQLite3, which is a lightweight database engine, uses
SQL as its query language, and Python's sqlite3
module allows you to execute SQL commands directly.
The four fundamental operations of persistent storage
are Create, Read, Update, and Delete (CRUD).
Here's a brief overview of using the sqlite3 module:
1. Connecting to a Database:
import sqlite3
# Connect to a database (or create it if it doesn't exist)
conn = sqlite3.connect('example.db')
2. Creating a Cursor:
A cursor is used to execute SQL statements and fetch
results.
# Create a cursor object
cursor = conn.cursor()
Here's a brief overview of using the sqlite3 module:
3. Creating a Table:
# Create a table if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)
''')
4. Inserting Data:
# Insert data into the table
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", (‘vikas',
29))
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", (‘ram', 30))
Here's a brief overview of using the sqlite3 module:
5. Committing Changes:
# Commit the changes
conn.commit()
6. Querying Data:
# Query data from the table
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
# Display the queried data
for row in rows:
print(row)
7. Closing Resources:
# Close the cursor and connection
cursor.close()
conn.close()
SQLite Methods:
Here's a brief explanation of the connect, cursor, execute, and close methods in
the context of SQLite with the sqlite3 module in Python:
1.connect Method:
• Purpose: Establishes a connection to an SQLite database.
• Syntax:
connect(database[, timeout, detect_types, isolation_level, check_same_thread,
factory, cached_statements, uri])
• Parameters:
database: The name of the SQLite database file.
timeout (optional): Timeout in seconds for blocking operations.
detect_types (optional): Determines if types should be detected.
isolation_level (optional): Isolation level for transactions.
check_same_thread (optional): Check if the same thread created the
connection.
factory (optional): Custom class for creating a cursor.
cached_statements (optional): Number of cached statements per
connection.
uri (optional): If True, interpret the database parameter as a URI.
SQLite Methods:
2. cursor Method:
• Purpose: Creates a cursor object used to execute SQL
commands and manage query results.
• Syntax:
cursor()
• Parameters: None
• Example:
cursor = conn.cursor()
3. execute Method:
• Purpose: Executes an SQL statement.
• Syntax:
execute(sql[, parameters])
• Parameters:
sql: The SQL statement to be executed.
parameters (optional): A tuple or dictionary containing
parameters for the SQL statement.
SQLite Methods:
Example:
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)",
(‘Vikas', 29))
4. close Method:
• Purpose: Closes the database connection and the cursor.
• Syntax:
close()
Example:
conn.close()
Connect to Database:
To connect to an SQLite database using the sqlite3 module in Python,
you can use the connect method.
Example:
import sqlite3
# Connect to the SQLite database (creates the database if it doesn't
exist)
conn = sqlite3.connect('example.db')
# Create a cursor
cursor = conn.cursor()
# Perform database operations here
# Close the connection when done
conn.close()
Create Table:
Below is an example of how to create a table in SQLite using the sqlite3 module in Python:
import sqlite3
# Connect to the SQLite database (creates the database if it doesn't exist)
conn = sqlite3.connect('example.db')
# Create a cursor
cursor = conn.cursor()
# Create a table named 'users'
cursor.execute('''CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)''')
# Commit the changes
conn.commit()
# Close the connection
conn.close()
• In the above example:
 We connect to the SQLite database using
sqlite3.connect('example.db').
We create a cursor using conn.cursor().
We use the execute method to run an SQL statement that creates a
table named 'users'. The table has three columns: 'id', 'name', and
'age'.
 The 'id' column is an INTEGER and is set as the primary key.
 The 'name' column is of type TEXT and cannot be NULL.
 The 'age' column is of type INTEGER.
The IF NOT EXISTS clause ensures that the table is only created if it
doesn't already exist.
We commit the changes to the database using conn.commit().
Finally, we close the connection using conn.close().
• Operations on Tables- Insert, Select, Update. Delete and
Drop Records.
Insert:
• In this example:
• We connect to the SQLite database and create a cursor as usual.
• We create a table named 'users' if it doesn't exist, with columns 'id',
'name', and 'age'.
• We define a list users_data containing tuples of name and age for
multiple users.
• We use the executemany method to insert multiple records into the
'users' table in a single operation. This is more efficient than using
execute multiple times.
• After inserting the records, we commit the changes to the database.
• We then select and print all records from the 'users' table to verify the
successful insertion.
• Operations on Tables- Insert, Select, Update. Delete and
Drop Records.
Select:
• In this example:
• We connect to the SQLite database and create a cursor as
usual.
• We create a table named 'users' if it doesn't exist, with
columns 'id', 'name', and 'age'.
• We insert records into the 'users' table using the executemany
method.
• We commit the changes to the database.
• We use the SELECT * FROM users SQL statement to
select all records from the 'users' table.
• We fetch all rows using fetchall() and print them
• Operations on Tables- Insert, Select, Update. Delete and
Drop Records.
Update:
• In this example:
• We connect to the SQLite database and create a cursor as usual.
• We create a table named 'users' if it doesn't exist, with columns 'id',
'name', and 'age'.
• We insert records into the 'users' table using the executemany method.
• We commit the changes to the database.
• We select and print all records from the 'users' table before the update.
• We use the UPDATE statement to modify the age of a user ('vikas') to
29.
• We commit the changes to the database.
• We select and print all records from the 'users' table after the update.
• Operations on Tables- Insert, Select, Update. Delete and
Drop Records.
Delete:
• In this example:
• We connect to the SQLite database and create a cursor as usual.
• We create a table named 'users' if it doesn't exist, with columns 'id',
'name', and 'age'.
• We insert records into the 'users' table using the executemany method.
• We commit the changes to the database.
• We select and print all records from the 'users' table before the delete.
• We use the DELETE statement to remove a specific user record
('vikas') from the 'users' table.
• We commit the changes to the database.
• We select and print all records from the 'users' table after the delete.
• Operations on Tables- Insert, Select, Update. Delete and
Drop Records.
Drop Records:
• We connect to the SQLite database and create a cursor.
• We create a table named 'users' if it doesn't exist.
• We insert records into the 'users' table using the executemany method.
• We commit the changes to the database.
• We select and print all records from the 'users' table before dropping.
• We use the DROP TABLE statement to drop the entire 'users' table,
effectively removing all records.
• We commit the changes to the database.
• We attempt to select from the 'users' table after dropping, resulting in
an OperationalError since the table no longer exists.

More Related Content

PPTX
trigger dbms
ODP
Introduction to triggers
PPTX
pl/sql Procedure
PPTX
Java GC
PPTX
Data Structures - Lecture 9 [Stack & Queue using Linked List]
PPTX
Doubly & Circular Linked Lists
PPTX
Stacks and Queue - Data Structures
trigger dbms
Introduction to triggers
pl/sql Procedure
Java GC
Data Structures - Lecture 9 [Stack & Queue using Linked List]
Doubly & Circular Linked Lists
Stacks and Queue - Data Structures

What's hot (20)

PPTX
Super Keyword in Java.pptx
PDF
Lesson 03 python statement, indentation and comments
PDF
PDF
SQL Outer Joins for Fun and Profit
PPT
Operator Overloading
PPTX
JAVA AWT
PDF
06. operator overloading
PPS
Single linked list
PDF
Methods in Java
PPT
Chapter 12 ds
DOCX
Learning sql from w3schools
PPT
Joins in SQL
PPTX
array of object pointer in c++
PPS
String and string buffer
PPTX
single linked list
PPT
Aggregate functions
PDF
8 python data structure-1
PPTX
Mathematical Analysis of Non-Recursive Algorithm.
PPTX
Polymorphism
Super Keyword in Java.pptx
Lesson 03 python statement, indentation and comments
SQL Outer Joins for Fun and Profit
Operator Overloading
JAVA AWT
06. operator overloading
Single linked list
Methods in Java
Chapter 12 ds
Learning sql from w3schools
Joins in SQL
array of object pointer in c++
String and string buffer
single linked list
Aggregate functions
8 python data structure-1
Mathematical Analysis of Non-Recursive Algorithm.
Polymorphism
Ad

Similar to Python SQLite3.pptx (20)

PPTX
SQLite 3 chapter 4 BCA Notes Python NEP syllabus
PPTX
Python SQite3 database Tutorial | SQlite Database
PPTX
3 PYTHON INTERACTION WITH SQLITE (concept of python)
PPTX
Sqlite3 databases
PDF
Sq lite python tutorial sqlite programming in python
PPTX
Chapter -7.pptx
DOCX
PPTX
Data Handning with Sqlite for Android
PDF
The sqlite3 commnad line tool
PPTX
PYTHON_DATABASE_CONNECTIVITY.pptxPYTHON_DATABASE
PPTX
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
DOCX
SQLiteWrittenExplanation
PPTX
Session #5 content providers
PPTX
python db connection samples and program
PPTX
UNIT V PYTHON.pptx python basics ppt python
ODP
Introduction4 SQLite
PPTX
Sq lite
PPTX
Create an android app for database creation using.pptx
SQLite 3 chapter 4 BCA Notes Python NEP syllabus
Python SQite3 database Tutorial | SQlite Database
3 PYTHON INTERACTION WITH SQLITE (concept of python)
Sqlite3 databases
Sq lite python tutorial sqlite programming in python
Chapter -7.pptx
Data Handning with Sqlite for Android
The sqlite3 commnad line tool
PYTHON_DATABASE_CONNECTIVITY.pptxPYTHON_DATABASE
PYTHON_DATABASE_CONNECTIVITY_for_class_12.pptx
SQLiteWrittenExplanation
Session #5 content providers
python db connection samples and program
UNIT V PYTHON.pptx python basics ppt python
Introduction4 SQLite
Sq lite
Create an android app for database creation using.pptx
Ad

More from VikasTuwar1 (20)

PPTX
CS_Departmeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeent BOS.pptx
PPT
orientation proddddddddddddddddddddgramme ppt.ppt
PPTX
jabeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeein.pptx
PPTX
kle pcjabineeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
PPT
Intwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwernet.ppt
PPTX
Introduction_to_computershfffffffffffffffffffffffffffffffffffffffffffffff_and...
PPT
introductiottttttttttttttttttttttttn_to_computers.ppt
PPTX
Unit-2_XMxvvxvxvxvLccccccccccccccccccccccccccc.pptx
PPTX
XSeyeyeyeyeyeyeyeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeS.pptx
PPTX
ldagwvwvbwbwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvpinjection.pptx
PPTX
xpathinvevevevwvwvwvwvwvwwwwwwwwwwwwwwwjection.pptx
PPTX
Uwvwwbwbwbwbwbwbwbnit-4 - web security.pptx
PPTX
Unitegergergegegegetgegegegegegeg-2-CSS.pptx
PPTX
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
PPTX
BSC notes of _HTML_Easyto understand lease see.pptx
PPTX
Unit-3.pptx
PPTX
Unit-1.pptx
PPTX
Unit-1.pptx
PPT
DataMining.ppt
PPTX
PPT-4.pptx
CS_Departmeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeent BOS.pptx
orientation proddddddddddddddddddddgramme ppt.ppt
jabeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeein.pptx
kle pcjabineeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
Intwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwernet.ppt
Introduction_to_computershfffffffffffffffffffffffffffffffffffffffffffffff_and...
introductiottttttttttttttttttttttttn_to_computers.ppt
Unit-2_XMxvvxvxvxvLccccccccccccccccccccccccccc.pptx
XSeyeyeyeyeyeyeyeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeS.pptx
ldagwvwvbwbwvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvpinjection.pptx
xpathinvevevevwvwvwvwvwvwwwwwwwwwwwwwwwjection.pptx
Uwvwwbwbwbwbwbwbwbnit-4 - web security.pptx
Unitegergergegegegetgegegegegegeg-2-CSS.pptx
Unitwwsbdsbsdbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4.pptx
BSC notes of _HTML_Easyto understand lease see.pptx
Unit-3.pptx
Unit-1.pptx
Unit-1.pptx
DataMining.ppt
PPT-4.pptx

Recently uploaded (20)

PDF
Trump Administration's workforce development strategy
PDF
Complications of Minimal Access Surgery at WLH
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Lesson notes of climatology university.
PPTX
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
PPTX
UNIT III MENTAL HEALTH NURSING ASSESSMENT
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
Anesthesia in Laparoscopic Surgery in India
Trump Administration's workforce development strategy
Complications of Minimal Access Surgery at WLH
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Computing-Curriculum for Schools in Ghana
Final Presentation General Medicine 03-08-2024.pptx
A systematic review of self-coping strategies used by university students to ...
Supply Chain Operations Speaking Notes -ICLT Program
01-Introduction-to-Information-Management.pdf
Lesson notes of climatology university.
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
UNIT III MENTAL HEALTH NURSING ASSESSMENT
Paper A Mock Exam 9_ Attempt review.pdf.
Microbial disease of the cardiovascular and lymphatic systems
What if we spent less time fighting change, and more time building what’s rig...
LDMMIA Reiki Yoga Finals Review Spring Summer
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Practical Manual AGRO-233 Principles and Practices of Natural Farming
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Anesthesia in Laparoscopic Surgery in India

Python SQLite3.pptx

  • 2. What is sqlite3 module in Python? SQLite3, which is a lightweight database engine, uses SQL as its query language, and Python's sqlite3 module allows you to execute SQL commands directly. The four fundamental operations of persistent storage are Create, Read, Update, and Delete (CRUD).
  • 3. Here's a brief overview of using the sqlite3 module: 1. Connecting to a Database: import sqlite3 # Connect to a database (or create it if it doesn't exist) conn = sqlite3.connect('example.db') 2. Creating a Cursor: A cursor is used to execute SQL statements and fetch results. # Create a cursor object cursor = conn.cursor()
  • 4. Here's a brief overview of using the sqlite3 module: 3. Creating a Table: # Create a table if it doesn't exist cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, name TEXT, age INTEGER ) ''') 4. Inserting Data: # Insert data into the table cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", (‘vikas', 29)) cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", (‘ram', 30))
  • 5. Here's a brief overview of using the sqlite3 module: 5. Committing Changes: # Commit the changes conn.commit() 6. Querying Data: # Query data from the table cursor.execute("SELECT * FROM users") rows = cursor.fetchall() # Display the queried data for row in rows: print(row) 7. Closing Resources: # Close the cursor and connection cursor.close() conn.close()
  • 6. SQLite Methods: Here's a brief explanation of the connect, cursor, execute, and close methods in the context of SQLite with the sqlite3 module in Python: 1.connect Method: • Purpose: Establishes a connection to an SQLite database. • Syntax: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri]) • Parameters: database: The name of the SQLite database file. timeout (optional): Timeout in seconds for blocking operations. detect_types (optional): Determines if types should be detected. isolation_level (optional): Isolation level for transactions. check_same_thread (optional): Check if the same thread created the connection. factory (optional): Custom class for creating a cursor. cached_statements (optional): Number of cached statements per connection. uri (optional): If True, interpret the database parameter as a URI.
  • 7. SQLite Methods: 2. cursor Method: • Purpose: Creates a cursor object used to execute SQL commands and manage query results. • Syntax: cursor() • Parameters: None • Example: cursor = conn.cursor() 3. execute Method: • Purpose: Executes an SQL statement. • Syntax: execute(sql[, parameters]) • Parameters: sql: The SQL statement to be executed. parameters (optional): A tuple or dictionary containing parameters for the SQL statement.
  • 8. SQLite Methods: Example: cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", (‘Vikas', 29)) 4. close Method: • Purpose: Closes the database connection and the cursor. • Syntax: close() Example: conn.close()
  • 9. Connect to Database: To connect to an SQLite database using the sqlite3 module in Python, you can use the connect method. Example: import sqlite3 # Connect to the SQLite database (creates the database if it doesn't exist) conn = sqlite3.connect('example.db') # Create a cursor cursor = conn.cursor() # Perform database operations here # Close the connection when done conn.close()
  • 10. Create Table: Below is an example of how to create a table in SQLite using the sqlite3 module in Python: import sqlite3 # Connect to the SQLite database (creates the database if it doesn't exist) conn = sqlite3.connect('example.db') # Create a cursor cursor = conn.cursor() # Create a table named 'users' cursor.execute('''CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER )''') # Commit the changes conn.commit() # Close the connection conn.close()
  • 11. • In the above example:  We connect to the SQLite database using sqlite3.connect('example.db'). We create a cursor using conn.cursor(). We use the execute method to run an SQL statement that creates a table named 'users'. The table has three columns: 'id', 'name', and 'age'.  The 'id' column is an INTEGER and is set as the primary key.  The 'name' column is of type TEXT and cannot be NULL.  The 'age' column is of type INTEGER. The IF NOT EXISTS clause ensures that the table is only created if it doesn't already exist. We commit the changes to the database using conn.commit(). Finally, we close the connection using conn.close().
  • 12. • Operations on Tables- Insert, Select, Update. Delete and Drop Records. Insert: • In this example: • We connect to the SQLite database and create a cursor as usual. • We create a table named 'users' if it doesn't exist, with columns 'id', 'name', and 'age'. • We define a list users_data containing tuples of name and age for multiple users. • We use the executemany method to insert multiple records into the 'users' table in a single operation. This is more efficient than using execute multiple times. • After inserting the records, we commit the changes to the database. • We then select and print all records from the 'users' table to verify the successful insertion.
  • 13. • Operations on Tables- Insert, Select, Update. Delete and Drop Records. Select: • In this example: • We connect to the SQLite database and create a cursor as usual. • We create a table named 'users' if it doesn't exist, with columns 'id', 'name', and 'age'. • We insert records into the 'users' table using the executemany method. • We commit the changes to the database. • We use the SELECT * FROM users SQL statement to select all records from the 'users' table. • We fetch all rows using fetchall() and print them
  • 14. • Operations on Tables- Insert, Select, Update. Delete and Drop Records. Update: • In this example: • We connect to the SQLite database and create a cursor as usual. • We create a table named 'users' if it doesn't exist, with columns 'id', 'name', and 'age'. • We insert records into the 'users' table using the executemany method. • We commit the changes to the database. • We select and print all records from the 'users' table before the update. • We use the UPDATE statement to modify the age of a user ('vikas') to 29. • We commit the changes to the database. • We select and print all records from the 'users' table after the update.
  • 15. • Operations on Tables- Insert, Select, Update. Delete and Drop Records. Delete: • In this example: • We connect to the SQLite database and create a cursor as usual. • We create a table named 'users' if it doesn't exist, with columns 'id', 'name', and 'age'. • We insert records into the 'users' table using the executemany method. • We commit the changes to the database. • We select and print all records from the 'users' table before the delete. • We use the DELETE statement to remove a specific user record ('vikas') from the 'users' table. • We commit the changes to the database. • We select and print all records from the 'users' table after the delete.
  • 16. • Operations on Tables- Insert, Select, Update. Delete and Drop Records. Drop Records: • We connect to the SQLite database and create a cursor. • We create a table named 'users' if it doesn't exist. • We insert records into the 'users' table using the executemany method. • We commit the changes to the database. • We select and print all records from the 'users' table before dropping. • We use the DROP TABLE statement to drop the entire 'users' table, effectively removing all records. • We commit the changes to the database. • We attempt to select from the 'users' table after dropping, resulting in an OperationalError since the table no longer exists.