VOOZH about

URL: https://www.geeksforgeeks.org/python/python-sqlite-connecting-to-database/

⇱ Python SQLite - Connecting to Database - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python SQLite - Connecting to Database

Last Updated : 7 Apr, 2026

An SQLite database can be connected to a Python program using the sqlite3.connect() method. It establishes a connection by opening the specified database file and creates the file if it does not already exist.

Establishing Database Connection

To interact with an SQLite database, we first need to establish a connection to it using the connect() method. If the specified database file doesn't exist, SQLite will create it automatically.

sqliteConnection = sqlite3.connect('database_name.db')

After establishing the connection, we need to create a cursor object to execute SQL queries on the database.

cursor = sqliteConnection.cursor()

SQL query to be executed can be written in form of a string, and then executed using the cursor.execute() method. and the results can be fetched from the server by using the fetchall() method.

Syntax:

query = 'SQL query;'
cursor.execute(query)
result = cursor.fetchall()

print('SQLite Version is {}'.format(result))

Example: Connecting to SQLite and Querying the Version

Below is an example that connects to an SQLite database, runs a simple query to retrieve the version of SQLite, and handles any potential errors during the process.

Output

👁 Image

Explanation:

  • sqlite3.connect('sql.db') establishes a connection to the SQLite database named sql.db. If the database doesn't exist, it will be created automatically.
  • cursor = sqliteConnection.cursor() creates a cursor object, which is used to interact with the database and execute SQL queries.
  • query SELECT sqlite_version(): fetches the SQLite version being used.
  • cursor.execute() method runs the query, and cursor.fetchall() retrieves the result.
  • except sqlite3.Error as error: block catches SQLite-related errors (e.g., connection or query issues).
  • error variable shows the specific problem, allowing the program to handle it without crashing.
Comment
Article Tags:
Article Tags: