Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
SQLite question
#3
(May-24-2023, 06:00 AM)DPaul Wrote: Hi,
I am using SQLite (version 2.6.0)
Somewhere in the code I need to check if there is an active connection to a database.

In mySQL there is something like "conn.is_connected()".
This seems to be missing in SQLite, or did I miss it?
thx,
Pau

Edit: seems to be missing in SQLite. Then we'll do conn = None or not None.

In SQLite, there is no built-in method like conn.is_connected() to check if there is an active connection to the database. However, you can use a try-except block to handle any exceptions that might occur when attempting to execute a query or interact with the database. If an exception is raised, it usually indicates that the connection is not active.

Here's an example of how you can check the connection status in SQLite using a try-except block:

import sqlite3

# Establish a connection to the SQLite database
connection = sqlite3.connect("your_database.db")

try:
    # Attempt to execute a simple query to check the connection
    cursor = connection.cursor()
    cursor.execute("SELECT 1")
    result = cursor.fetchone()
    if result[0] == 1:
        print("Connection is active")
    else:
        print("Connection is not active")
except sqlite3.Error as error:
    print("Connection is not active:", error)
finally:
    # Close the connection
    connection.close()
In this example, if the query successfully executes and returns a result of 1, it indicates that the connection is active. If an exception is raised, it means that the connection is not active. Finally, the connection.close() statement ensures that the connection is closed regardless of the outcome.
Reply


Messages In This Thread
SQLite question - by DPaul - May-24-2023, 06:00 AM
RE: SQLite question - by rob101 - May-24-2023, 03:44 PM
RE: SQLite question - by DigiGod - May-25-2023, 11:10 PM
RE: SQLite question - by DPaul - May-26-2023, 06:10 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020