Not sure about whether I should and how to close a Connection in SQLite.swift. Will it cause thread/memory leak?
Asked
Active
Viewed 3,446 times
3 Answers
2
Normally the database is closed when the Connection
variable is out of its using scope and reclaimed by the trash-collecting system (in the deinit
function). But sometimes it is one of your class's attributes, so you might want to close it manually in the middle of some functions. Hence this code works:
sqlite3_close(db.handle)
where db
has the type of Connection
. You can then override the database file or delete it, no warnings will be raised.
Anyways, I highly recommend you design your code in a cautious way to let the system frees the handle.

Eric Yuan
- 1,213
- 11
- 13
0
- Although SQLite does close connections automatically. To avoid potential race conditions from dangling threads. I add this to the end of my generic Swift query function for completeness.
if sqlite3_close(db) != SQLITE_OK {
print("error closing database")
}
Where
var db: OpaquePointer?
var databaseFullPath: String = "" /// Location database.
if sqlite3_open(databaseFullPath, &db) != SQLITE_OK {
print("error opening database")
}
Additional Information: sqlite3_close() documentation.

Dr Ian Gregory
- 184
- 6
-1
Sqlite connection will close automatically if u don't do it manually.
for e.g:
try {
conn.close();
}
catch (Exception ex) {
System.out.println ("Error");
return false;
}

Manoj Salvi
- 2,639
- 1
- 17
- 21

xs6
- 860
- 8
- 18
-
If I hold the Connection as a Singleton in iOS app, when will the connection be "automatically" closed? – henrichen Nov 27 '15 at 07:24
-
Normaly when the process will be closed. In windows it is when the application get the close command. When the process gets killed (for e.g. by a crash) the db will be not closed automatically! It is better to open and close the DB after every statement. – xs6 Nov 27 '15 at 07:29
-
1There should be no need to close the db after every statement. Connection objects are closed upon deinit. Any singleton object will generally "leak" for the duration of an app's lifecycle, but this is always going to be a minimal amount of memory (a single set of memory rather than a constantly growing leak). – stephencelis Nov 27 '15 at 13:34
-
@stephencelis, Thanks. So Connection object will be closed in deinit. I can just let ARC do the job. – henrichen Nov 30 '15 at 07:30
-
1I am also using sqlite in my project. but somehow if i fire lots of queries then cpu usage going over 200 %. i am also not closing database connection. – Jay Patel Sep 19 '17 at 04:30