May-25-2023, 11:10 PM
(This post was last modified: May-26-2023, 11:47 AM by Larz60+.
Edit Reason: Please use bbcode tags
)
(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.