GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • w3resource
  • Front End
  • HTML
  • CSS
  • JavaScript
  • HTML5
  • Schema.org
  • php.js
  • Twitter Bootstrap
  • Responsive Web Design tutorial
  • Zurb Foundation 3 tutorials
  • Pure CSS
  • HTML5 Canvas
  • JavaScript Course

This view

  • Original page
  • New address

GeezerVison is showing www.w3resource.com — Python SQLite Tutorial: Basics of Working with Databases

  • Home
  • ▼Introduction to Python
  • Python Home
  • Python 2 vs 3
  • Python Installation
  • Python IDLE
  • ▼Python Basic
  • Python Syntax
  • Python Print Statement
  • Python Variable
  • Python Data Type
  • Python Operators
  • Python If elif else
  • Python For Loop
  • Python While Loop
  • Python break, continue
  • ▼Data Handling and Structures
  • Python String
  • Python Lists
  • Python Dictionary
  • Python Tuples
  • Python Sets
  • Python Bytes, Bytearray
  • Python Advanced Data Structure
  • ▼Date and Time
  • Python Date and Time
  • Python Calendar Module
  • ▼Functions and Modules
  • Python User define function
  • Python Built-in Functions
  • Python Module
  • Python Functions Examples
  • ▼File Handling and I/O
  • Python File Handling
  • ▼Object-Oriented Programming
  • Python Classes
  • ▼Advanced Programming Constructs
  • Python Iterators
  • Python Generators
  • Python Functional Programming
  • Python Multithearding
  • ▼Regular Expressions
  • Python Regular Expressions
  • ▼Error Handling and Debugging
  • Python Exception Handling
  • Python Testing and Debugging
  • ▼Database Interaction
  • Python SQlite Database
  • Python SQLalchemy ORM
  • ▼Advanced Python Topics
  • Advanced Python Topics
  • Python Standard Library
  • ▼Web Programming
  • CGI Programming
  • ▼Python Miscellaneous
  • Python-docx: Create and Manipulate
  • Software Frameworks
  • Floor Division in Python
  • Thonny Python IDE
  • pip install mysql-connector-python
  • Astral Python in 2026
  • PyCharm 2026 The Ultimate Guide
  • Python for Data Analysis in 2026
  • Self-Driving Python Server
  • Python-Native Hypermedia UI
  • Building Dashboards with Pythons
  • Building an Educational HTTP Server
  • Python-First Rapid App Generator
  • Markdown-Native Personal Site Framework
  • pyRAP Framework
  • Hypermedia-Driven Python Framework
  • Shinylives Reactive Framework
  • ASGIMachine: HTTP Decision Graph Framework
  • Embedded Web Framework for MicroPython
  • ..More to come..

Python SQLite: Basics of Working with SQLite Databases

Last update on April 20 2026 12:16:34 (UTC/GMT +8 hours)

Introduction to Python SQLite

SQLite is a lightweight, disk-based database that doesn't require a separate server process. Python comes with built-in support for SQLite through the sqlite3 module, which allows us to create, manipulate, and query SQLite databases easily.

Following tutorial provides a foundational understanding of SQLite in Python, which is useful for developing lightweight, database-driven applications.

Example 1: Connecting to an SQLite Database

This example demonstrates how to connect to an SQLite database. If the database does not exist, it will be created.

Code:

import sqlite3
# Connect to an SQLite database (or create it if it doesn't exist)
connection = sqlite3.connect('sql_data.db')  # Creates or opens a file named 'sql_data.db'

# Create a cursor object to interact with the database
cursor = connection.cursor()

# Close the connection
connection.close()

Explanation:

  • Connection: 'sqlite3.connect('example.db')' opens a connection to the SQLite database file named 'example.db'. If the file does not exist, it creates a new one.
  • Cursor: The 'cursor' object is used to execute SQL queries and retrieve data.
  • Closing the Connection: 'connection.close()' closes the connection to the database, which is a good practice to free up resources.

Example 2: Creating a Table

This example shows how to create a table named 'users' in the SQLite database.

Code:

import sqlite3
# Connect to the SQLite database
connection = sqlite3.connect('sql_data.db')
cursor = connection.cursor()

# Create a table named 'users'
cursor.execute('''CREATE TABLE IF NOT EXISTS users (
                    id INTEGER PRIMARY KEY,
                    name TEXT NOT NULL,
                    age INTEGER NOT NULL
                )''')

# Commit the changes to save them
connection.commit()

# Close the connection
connection.close()

Explanation:

  • SQL Command: The 'CREATE TABLE SQL' command is used to create a new table named users with three columns: 'id', 'name', and 'age'.
  • IF NOT EXISTS: Ensures the table is only created if it does not already exist, preventing errors.
  • Commit: 'connection.commit()' saves the changes made to the database.

Example 3: Inserting Data into a Table

This example demonstrates how to insert data into the 'users' table.

Code:

import sqlite3
# Connect to the SQLite database
connection = sqlite3.connect('sql_data.db')
cursor = connection.cursor()

# Insert data into the 'users' table
cursor.execute("INSERT INTO users (name, age) VALUES ('Martyn Shyam', 30)")
cursor.execute("INSERT INTO users (name, age) VALUES ('Praveen Juliet', 25)")
# Commit the changes to save them
connection.commit()
# Close the connection
connection.close()

Explanation:

  • INSERT Statement: The ‘INSERT INTO’ SQL statement is used to insert new rows of data into the ‘users’ table.
  • Values: Data values are directly provided in the SQL query for simplicity.
  • Multiple Inserts: Multiple ‘execute’ calls can be used to insert several rows.

Example 4: Querying Data from a Table

This example shows how to retrieve data from the 'users' table.

Code:

import sqlite3
# Connect to the SQLite database
connection = sqlite3.connect('sql_data.db')
cursor = connection.cursor()

# Query data from the 'users' table
cursor.execute("SELECT * FROM users")

# Fetch all rows from the executed query
rows = cursor.fetchall()

# Print the results
for row in rows:
    print(row)

# Close the connection
connection.close()

Output:

(1, 'Martyn Shyam', 30)
(2, 'Praveen Juliet', 25)

Explanation:

  • SELECT Statement: The 'SELECT * FROM users' SQL command retrieves all columns ('*') from the 'users' table.
  • Fetching Data: 'cursor.fetchall()' fetches all the results of the executed query as a list of tuples.
  • Iteration: A 'for' loop is used to print each row retrieved from the table.

Example 5: Updating Data in a Table

This example demonstrates how to update existing data in the 'users' table.

Code:

import sqlite3
# Connect to the SQLite database
connection = sqlite3.connect('sql_data.db')
cursor = connection.cursor()

# Update data in the 'users' table
cursor.execute("UPDATE users SET age = 34 WHERE name = 'Praveen Juliet'")

# Commit the changes to save them
connection.commit()

# Close the connection
connection.close()

Explanation:

  • UPDATE Statement: The 'UPDATE' SQL command modifies the data in the table. It changes the age of the user named "Praveen Juliet" to 34.
  • WHERE Clause: The ‘WHERE’ clause specifies which rows should be updated.

Example 6: Deleting Data from a Table

This example shows how to delete data from the 'users' table.

Code:

import sqlite3
# Connect to the SQLite database
connection = sqlite3.connect('sql_data.db')
cursor = connection.cursor()

# Delete data from the 'users' table
cursor.execute("DELETE FROM users WHERE name = 'Praveen Juliet'")

# Commit the changes to save them
connection.commit()

# Close the connection
connection.close()

Explanation:

  • DELETE Statement: The 'DELETE' SQL command removes rows from the table. Here, it deletes the row where the name is "Praveen Juliet".
  • WHERE Clause: Ensures only the specified rows are deleted.

Example 7: Using Parameters to Prevent SQL Injection

This example shows how to use parameters to prevent SQL injection attacks.

Code:

import sqlite3
# Connect to the SQLite database
connection = sqlite3.connect('sql_data.db')
cursor = connection.cursor()

# Insert data using parameters to prevent SQL injection
name = "Gurutz Irene"
age = 40
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", (name, age))

# Commit the changes to save them
connection.commit()

# Close the connection
connection.close()

Explanation:

  • Parameters: Use placeholders ('?') and pass data as a tuple to safely insert data into the table.
  • SQL Injection Prevention: This method prevents malicious input from executing harmful SQL commands.

PREV : Python Testing and Debugging
NEXT :Python SQLAlchemy

Test your Python skills with w3resource's quiz



Follow us on Facebook and Twitter for latest update.


  • Daily Coding Challenges & Projects
  • Weekly Trends and Language Statistics



You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.