mercredi 1 avril 2015

How to properly close connection to SQLite database?

I have a problem that I suddenly get a lot of SQLite3 Operational errors - my database is locked. I think it is because I open the database for quite many times in my program. So, how do I ensure this isn't happening?



def getID(databasepath):
con = lite.connect(databasepath)
with con:
cur = con.execute("SELECT userid, name from Table")
con.commit()
rows = [[x[0], x[1]] for x in cur]
con.close()
return rows

def findIDsomewhereElse(databasepath):
con = lite.connect(databasepath)
with con:
cur = con.execute("SELECT userid FROM table2")
con.commit()
all_rows = cur.fetchall()
all_rows = sorted(all_rows, key=itemgetter(0), reverse=True)
con.close()
return all_rows


Main:



id = getId('firstpath')
userid = id[0]
con = lite.connect('secondpath')
with con:
cur = con.execute("SELECT max(time) FROM enteringSing WHERE userid = {userid}".format(userid = userid))
con.commit()
con.close()
newfind = findIDsomewhereElse('secondpath')
con = lite.connect('secondpath')
with con:
con.executemany("INSERT INTO table4(columns) VALUES(?)", allrows)
con.commit()
con.close()


So I connect to that database fairly often, is that the problem? I realize i probably should probably put the con lite connect outside the methods? But then again, I use a total of two databases.


Aucun commentaire:

Enregistrer un commentaire