Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a SQLite3 database is connected in Python?

Tags:

python

sqlite

Question 1: I have an SQLite3 connection in Python. How can I checked whether it is connected or not? I know that if sqlite3.connect() fails, an exception is raised, but if I or some closes the connection, how can I check this and reopen it if necessary?

Question 2: I can move the file in the file system while the connection is open (deletion is not possible). The database then becomes readonly, for whatever reason. If I move it back, it works as if nothing happened. Can anybody explain this? Should I check isfile(dbpath) before access?

like image 663
Fabian Avatar asked Feb 12 '16 16:02

Fabian


1 Answers

"try ... except" works pretty well too

import sqlite3 as mdb
def chk_conn(conn):
     try:
        conn.cursor()
        return True
     except Exception as ex:
        return False

myconn = mdb.connect('test.db')
print(chk_conn(myconn))

Out: True

myconn.close()
print(chk_conn(myconn))

Out: False

like image 78
Nikolai Zaitsev Avatar answered Oct 20 '22 10:10

Nikolai Zaitsev