search

Home  >  Q&A  >  body text

python - 每次操作数据库的时候需要关闭么?

每次操作数据库的时候需要关闭么? 会不会自动关闭,还是自己关闭,哪种方式好

迷茫迷茫2841 days ago1016

reply all(4)I'll reply

  • 阿神

    阿神2017-04-17 11:21:25

    1 needs to be closed every time
    2 After the timeout, most DBMS (and their SDKs) will disconnect the client at the TCP level.
    3 Be sure to develop the habit of manual shutdown (manual refers to explicitly calling the shutdown method. Of course, you can write an automated encapsulation to call the shutdown, or the shutdown is encapsulated in some SDKs). This is not a good habit. It’s not a matter of bad habits, but something that must be done.

    Because database resources are precious (the number of connections is precious) if you do not close it, waiting for automatic release may take a very long time. During this time, other thread processes will not be able to use this connection resource. If it is not closed everywhere, it will be very difficult. It is easy to run out of connections after several operations. (The number of connections for many "large" databases is only 10-20)

    reply
    0
  • 黄舟

    黄舟2017-04-17 11:21:25

    用with statement

    http://docs.python.org/2/reference/co...

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 11:21:25

    • Generally speaking, this problem is solved through libraries. Developers only need to operate according to the specifications of the calling library, such as sqlalchemy.
    • If the framework/library explicitly provides a shutdown operation, please call it - generally it is bound to the basic framework (such as a web framework) through inheritance or other abstract methods, and there is no need to write your own shutdown code every time you interact with the database. .
    • Finally, you have to know that connecting to the database is actually a very expensive operation, so it is actually impossible to close the database for every request connection. At this time, the so-called "close" operation provided by the framework or library should be accurately called "recycling", which is usually recycled to a connection pool and can then be called by other processes/threads.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 11:21:25

    If the rs cannot be closed this time and needs to be handed over to the next program method for use, it is recommended that the rs and connection must be closed immediately after the next program is completed. Otherwise, the database resources will be occupied all the time. In this case, have you considered the feelings of the database? . .

    reply
    0
  • Cancelreply