Connect to SQLite using Python

You can connect to SQLite from Python using Devart ODBC Driver for SQLite.

Install the pyodbc library

Run the following command to install the pyodbc library.

pip install pyodbc

Define a connection string

An ODBC connection requires a connection string, which can either use a predefined DSN or be specified through connection string parameters (a DSN-less connection).

For information about available parameters, see Connection string parameters.

DSN connection string

You can use a connection string with a predefined DSN.

connectionString = "DSN=your_dsn"

For information on configuring a DSN on specific operating systems, see instructions for Windows, macOS, or Linux.

DSN-less connection string

You can establish a connection without a DSN by specifying all necessary parameters directly in the connection string.

For more information, see DSN-less connections.

Connect to SQLite

The following Python code demonstrates how to connect to SQLite and fetch data using the ODBC driver.

# Import the pyodbc library for ODBC connections
import pyodbc

# Define an ODBC connection string
connectionString = "your_connection_string"

connection = pyodbc.connect(connectionString)

# Create an object to interact with a data source
cursor = connection.cursor()

# Execute a SQL query
query = "SELECT id, name FROM employees"
cursor.execute(query)

# Fetch and print the query results
print("Query results:")
for row in cursor.fetchall():
    # Output each tuple of the query results to the console
    print(row)

# Close the cursor and the connection
cursor.close()
connection.close()