简体   繁体   中英

Can a connection to postgresql using psycopg2 hold for 24+ hours?

I have a bot running 24/7 that accesses a PostgreSQL database. My first implementation of it would create a connection and close it for every transaction (first time learning SQL) but I learned that it takes a long time to create/close all these connections.
I made a small code to test the difference and got the following:

>>>test.py
100 tries: 
26.547296285629272 s (non persistent)
1.3095812797546387 s (persistent)

My question is can a persistent connection hold for 24+ hours? if not can I check for it and reconnect?

There is no inherent limit on the age of a connection. If you operating through a firewall or gateway though, it might interfere with attempts to hold one indefinitely. And of course if you ever take the server down for maintenance or cold backup, that will also break the connection.

The classic way to "ping" a suspect connection in PostgreSQL is to issue select 1; . Some connection poolers will do this for you. You should probably use one, rather than inventing your own. Assuming you need one in the first place--while establishing connections is slow, it shouldn't be nearly as slow as your mysterious benchmark is showing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM