Python自动重连postgre数据库
时间: 2023-12-02 11:06:34 浏览: 112
可以使用 psycopg2 模块来实现 Python 自动重连 postgre 数据库。可以使用以下代码:
```
import psycopg2
from psycopg2 import OperationalError
# 构建连接参数
db_params = {
"dbname": "your_db_name",
"user": "your_username",
"password": "your_password",
"host": "your_host",
"port": "your_port"
}
# 定义连接和游标对象
con = None
cursor = None
def create_db_connection():
global con, cursor
try:
# 尝试建立连接
con = psycopg2.connect(**db_params)
cursor = con.cursor()
print("连接已建立成功!")
except OperationalError as e:
# 如果建立连接失败,则打印错误信息并执行重连
print(f"连接建立失败,错误信息为:{e}")
reconnect()
def reconnect():
global con, cursor
while True:
print("进行重连...")
try:
# 尝试重新建立连接
con = psycopg2.connect(**db_params)
cursor = con.cursor()
print("连接已重新建立成功!")
break
except OperationalError as e:
# 如果重新建立连接失败,则等待 5 秒后重试
print(f"连接重新建立失败,错误信息为:{e}")
time.sleep(5)
def execute_query(query):
global con, cursor
try:
# 尝试执行查询
cursor.execute(query)
con.commit()
print("查询已执行成功!")
except OperationalError as e:
# 如果执行查询失败,则打印错误信息并执行重连
print(f"查询执行失败,错误信息为:{e}")
reconnect()
execute_query(query)
# 测试连接
create_db_connection()
# 测试执行查询
execute_query("SELECT * FROM your_table_name")
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)