python - 如何使用多个脚本安全连接到 postgres
问题描述
我已经开始学习如何使用 Python 编写 psycopg2 代码。我所做的是我的脚本很少。让我们举个例子,它最多可以有 150 个连接,我们知道,我们不能同时连接超过 100 个连接。我发现每当我想进行数据库查询/执行时 - 然后我连接到数据库,执行然后关闭数据库。但是我确实相信打开和关闭新连接非常昂贵并且应该更长寿。
我做了这样的事情:
DATABASE_CONNECTION = {
"host": "TEST",
"database": "TEST",
"user": "TEST",
"password": "TEST"
}
def get_all_links(store):
"""
Get all links from given store
:param store:
:return:
"""
conn = psycopg2.connect(**DATABASE_CONNECTION)
sql_update_query = "SELECT id, link FROM public.store_items WHERE store = %s AND visible = %s;"
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
try:
data_tuple = (store, "yes")
cursor.execute(sql_update_query, data_tuple)
test_data = [{"id": links["id"], "link": links["link"]} for links in cursor]
cursor.close()
conn.close()
return test_data
except (Exception, psycopg2.DatabaseError) as error:
print("Error: %s" % error)
cursor.close()
conn.rollback()
return 1
def get_all_stores():
"""
Get all stores in database
:return:
"""
conn = psycopg2.connect(**DATABASE_CONNECTION)
sql_update_query = "SELECT store FROM public.store_config;"
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
try:
cursor.execute(sql_update_query)
test_data = [stores["store"] for stores in cursor]
cursor.close()
conn.close()
return test_data
except (Exception, psycopg2.DatabaseError) as error:
print("Error: %s" % error)
cursor.close()
conn.rollback()
return 1
我想知道如何使它尽可能有效,因为我可以将很多脚本连接到数据库但仍然没有遇到 max_connection 问题?
我忘记补充说我连接的方式是我有多个脚本等:
test1.py
test2.py
test3.py
....
....
每个脚本都为自己运行
他们都有一个导入database.py
,其中包含我之前展示过的以下代码。
更新:
from psycopg2 import pool
threaded_postgreSQL_pool = psycopg2.pool.ThreadedConnectionPool(1, 2,
user="test",
password="test",
host="test",
database="test")
if (threaded_postgreSQL_pool):
print("Connection pool created successfully using ThreadedConnectionPool")
def get_all_stores():
"""
Get all stores in database
:return:
"""
# Use getconn() method to Get Connection from connection pool
ps_connection = threaded_postgreSQL_pool.getconn()
sql_update_query = "SELECT store FROM public.store_config;"
ps_cursor = ps_connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
try:
ps_cursor.execute(sql_update_query)
test_data = [stores["store"] for stores in ps_cursor]
ps_cursor.close()
threaded_postgreSQL_pool.putconn(ps_connection)
print("Put away a PostgreSQL connection")
return test_data
except (Exception, psycopg2.DatabaseError) as error:
print("Error: %s" % error)
ps_cursor.close()
ps_connection.rollback()
return 1
解决方案
没错,建立数据库连接很昂贵;因此,您应该使用连接池。但是没有必要重新发明轮子,因为psycopg2 具有内置的连接池:
使用psycopg2.pool.SimpleConnectionPool
or psycopg2.pool.ThreadedConnectionPool
(取决于您是否使用线程)并使用getconn()
andputconn()
方法来获取或返回连接。
推荐阅读
- arrays - 如何在其他已排序的数组中找到一个未排序的元素?(在 C 中)
- go - 按整数的分数休眠
- discord - 使用 fetchBans() 在 BansCollection 中找不到被禁止的用户
- c# - C# Roslyn 是否可以在 Android 上工作(使用 Xamarin)?
- c - 为什么要使用 cat 打开交互式 shell?
- python - 石墨烯不执行查询
- r - 在 r 中创建一个函数,该函数创建列名,然后使用这些相同的列名
- c# - 如何避免从下拉列表中选择默认值
- .net - 如果只有一个 UI 线程,如何同时激活多个事件处理程序?
- python - Python:用列的唯一现值填充数据框中的列