Answer the question
In order to leave comments, you need to log in
What for to close the cursor and connection to a DB?
Unless at the end of the script, the memory will not be freed? What for to close the cursor and connection to a DB?
And another question: why if you close the cursor after the connection, then no error occurs (the cursor uses the connection)? It is not logical why the cursor is not automatically closed when the connection is closed?
conn.commit()
conn.close()
cursor.close()
Answer the question
In order to leave comments, you need to log in
This is called sustainable good practice, which allows you to avoid a large number of mistakes in the future.
First, we need to define the terminology:
cursor - The driver class through which the interaction with the database takes place.
connection - The database connection class.
Any database has a maximum allowable number of connections. As well as the maximum allowable number of open cursors.
If you do not close, sooner or later you will hit the limit.
Also, it should be remembered that the transaction starts before the request is executed, and with certain database settings, at the time of the transaction, the tables are locked and do not allow other threads or programs to use them. By default, a transaction is created before the first query to the database is executed, and all subsequent queries are executed in the context of this transaction. And long transactions do not lead to anything good.
You also need to understand that when you create a connection to the database, you have a certain amount of RAM that is necessary for this. If you produce a lot of connections - you can gobble up all the memory.
Also, in the case of a heavy load and a large application, some kind of bug may creep in and non-closable connections can spoil enough nerves.
If you don't want to permanently close the connection and cursors, you can code through the with construct. Then the connection and the cursor will be closed automatically after the block of code in the construct is executed.
As a result:
1) Closing allows you to avoid errors associated with the use of the same connections in different threads.
2) Doesn't waste your RAM to make unnecessary connections.
3) Does not clog the database with unnecessary connections.
4) Allows you to properly manage transactions, and do only certain actions in a particular transaction, and not shove everything into a heap.
5) You do not hit the connection limit and do not get unnecessary errors about this.
6) You don't get errors about one connection trying to interact with a table or data created in another connection that is locked or not currently shared.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question