Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

Python SQLite – Connecting to Database

To connect to an SQLite database from Python, you need to use the `sqlite3` module, which comes bundled with Python. This module provides functions and classes to interact with SQLite databases. Here’s how you can connect to an SQLite database:

“`python
import sqlite3

# Connect to the SQLite database
connection = sqlite3.connect(‘example.db’)

# If the database doesn’t exist, it will be created automatically

# Close the database connection
connection.close()
“`

In the code above:

– We import the `sqlite3` module.
– We use the `sqlite3.connect()` function to establish a connection to the SQLite database. You need to provide the name of the database file as an argument to this function. If the specified database file does not exist, SQLite will create it automatically.
– After performing the required database operations, it’s essential to close the database connection using the `close()` method on the connection object.

If you’re connecting to an SQLite database in memory (i.e., creating a temporary database that exists only during the runtime of your Python program), you can pass the special string `:memory:` as the database file name:

“`python
import sqlite3

# Connect to an SQLite database in memory
connection = sqlite3.connect(‘:memory:’)

# Perform database operations…

# Close the database connection
connection.close()
“`

This is useful for temporary data storage or for testing purposes where you don’t need to persist data beyond the program’s execution.

File-based database
To connect to an SQLite database stored in a file, you just need to specify the path to the database file when calling the `connect()` function. Here’s how you can connect to an SQLite database stored in a file:

“`python
import sqlite3

# Connect to the SQLite database stored in a file
connection = sqlite3.connect(‘path/to/database.db’)

# If the specified database file does not exist, SQLite will create it automatically

# Close the database connection
connection.close()
“`

In the code above:

– We import the `sqlite3` module.
– We use the `sqlite3.connect()` function to establish a connection to the SQLite database. Replace `’path/to/database.db’` with the actual path to your SQLite database file. If the specified database file does not exist, SQLite will create it automatically.
– After performing the required database operations, it’s essential to close the database connection using the `close()` method on the connection object.

 

Join the conversation