How expensive is sqlite3.connect and close in SQLite?

I use connect () and cursor () to use SQLite

self.connector = sqlite3.connect (self.dbFile)
self.cursor = self.connector.cursor ()

And close () to stop using it.

self.cursor.close ()

How expensive (in terms of processing time) are they? Is it so expensive that you need to use it only absolutely necessary? Or, is it just fine to use it several times in a function?

ADDED

I tested the following code. proc1 () uses code that opens and closes all the time the request is executed, and proc2 () is run only once.

from sqlite import *
import timeit
import math

def proc1():
    db = SQLiteDB("./example.db", False)
    db.getOpenRunClose("SELECT * from Benchmark")
    db.getOpenRunClose("SELECT * from Benchmark")
    db.getOpenRunClose("SELECT * from Benchmark")
    db.getOpenRunClose("SELECT * from Benchmark")
    db.getOpenRunClose("SELECT * from Benchmark")
    db.getOpenRunClose("SELECT * from Benchmark")

def proc2():
    db = SQLiteDB("./example.db")
    res = db.runSQLToGetResult("SELECT * from Benchmark")
    res = db.runSQLToGetResult("SELECT * from Benchmark")
    res = db.runSQLToGetResult("SELECT * from Benchmark")
    res = db.runSQLToGetResult("SELECT * from Benchmark")
    res = db.runSQLToGetResult("SELECT * from Benchmark")
    res = db.runSQLToGetResult("SELECT * from Benchmark")
    db.close()

if __name__ == '__main__':
    t = timeit.Timer(proc1)
    count = 5000
    print t.timeit(count) / count

    t = timeit.Timer(proc2)
    count = 5000
    print t.timeit(count) / count

The result is as follows.

0.00157478599548
0.000539195966721
+3
source share
3 answers

- , - , [1]. , , , ( , ), . , , ( ), . ( - , DB, .)

; , . , . ? , SQL; SQL-, , . () .


[1] , , . .

+4

- . , sqlite , . "fopen" - sqlite.

, , , . , , , , , , , .

"" . , , , sqlite sql.

+1

A connection is more than just opening a file. As soon as you run any database queries, it should parse all the SQL in the sqlite_master table. Therefore, the time to connect depends on the complexity of the database. Simple databases can be connected in a few milliseconds, but larger ones will take more. Our clock is approximately 45 ms (more than a hundred tables, several hundred triggers).

+1
source

Source: https://habr.com/ru/post/1765534/


All Articles