创建一个KingbaseES的连接池是一个比较耗时及耗资源的操作,所在在ksycopg2中提供了pool模块。这个模块提供了几个纯Python类,它们直接在客户端程序中实现简单的连接池。
- 模块组成
1.1. 基类
类ksycopg2.pool.AbstractConnectionPool(minconn,maxconn,*args,kwargs)
实现通用的基于键的池化代码的基类。
新的minconn连接会自动创建。该池将最多支持约maxconn连接。*args和kwargs被传递给connect()函数。
预计子类将实现以下方法:
getconn(key=None)
从池中获取连接。
在关键的参数是可选的:如果使用的话,连接将被关联到钥匙,并呼吁getconn()再次使用相同的密钥将返回相同的连接。
putconn(conn,key=None,close=False )
放下一个连接。
如果close是True,则丢弃池中的连接。 key应该与getconn()对应。
closeall( )
关闭池处理的所有连接。
请注意,所有连接都已关闭,包括应用程序最终使用的连接。
1.2. 子类 - SimpleConnectionPool
Class ksycopg2.pool.SimpleConnectionPool(minconn,maxconn,*args,**kwargs)
不能跨不同线程共享的连接池。
注意:这个池类只对单线程应用程序有用。
1.3. 子类 - ThreadedConnectionPool
Class ksycopg2.pool.ThreadedConnectionPool(minconn,maxconn,*args,**kwargs)
与线程模块一起使用的连接池。
注意:这个池类可以安全地用于多线程应用程序。
- 连接参数解析
2.1. 连接参数解析
minconn:最小连接池大小
maxconn:最大连接池大小
host:指定运行 kingbaseES 的主机名
dbname:要连接的 kingbaseES 数据库。
user:要连接的用户名。
password:要连接的密码。
port:kingbaseES 服务器的 TCP 端口
2.2. 使用参数连接
kbpool = PersistentConnectionPool(1, 100, dbname=kb_name, user=kb_user, host=kb_host, password=kb_pw, port=kb_port))
2.3. 使用dns连接
kbsql_config = {
‘user’:‘system’,
‘password’:‘123’,
‘host’:‘192.168.29.102’,
‘port’:‘54322’,
‘database’:‘test’
}
pgpool = PersistentConnectionPool(1, 100, kbsql_config)
- 使用用例
from contextlib import contextmanager
from threading import Semaphore
import ksycopg2
#from ksycopg2 import pool, extersions
from ksycopg2.pool import
ThreadedConnectionPool,SimpleConnectionPool,AbstractConnectionPool
kbpool = ThreadedConnectionPool(1, 5, “dbname=test user=system host=192.168.29.102 password=123 port=54322”) #多进程
#kbpool = SimpleConnectionPool(1, 5, “dbname=test user=system host=192.168.29.102 password=123 port=54322”) #单进程
#kbpool = AbstractConnectionPool(1, 100, “dbname=test user=system host=192.168.29.102 password=123 port=54322”)
def conn_exe(sql):
conn = kbpool.getconn() # 获取连接
cursor = conn.cursor() # 获取cursor
cursor.execute(sql)
conn.commit() # 没次操作都要提交
kbpool.putconn(conn) # 放回连接, 防止其他程序kb无连接可用
return cursor
def fetchone_sql(sql):
cursor = conn_exe(sql)
fetchone = cursor.fetchone()
cursor.close()
return fetchone
def fetchall_sql(sql):
cursor = conn_exe(sql)
fetchall = cursor.fetchall()
cursor.close()
return fetchall
def get_insert_id(sql):
cursor = conn_exe(sql)
cursor.close()
def run_sql(sql):
cursor = conn_exe(sql)
cursor.close()
if name == ‘main’:
conn_exe(“drop table if exists pool_test;”)
conn_exe(“create table pool_test(id1 int, name varchar(100));”)
get_insert_id("insert into pool_test values(1, 'name1');")
get_insert_id("insert into pool_test values(2, 'name2');")
get_insert_id("insert into pool_test values(3, 'name3');")
print(fetchone_sql("select * from pool_test;"))
print(fetchall_sql("select * from pool_test;"))



