汇集多个mysql连接的问题

时间:2015-10-06 18:07:36

标签: python mysql connection-pooling mysql-python mysql-connector

我尝试实现mysql池,但是有一个问题: 我正在从一个env变量解析mysql连接凭证,这个变量基本上是一个字典,并且里面有多个数据库凭据。

   dict={'db1': {'username':**** ,'password':**** ,'database':*****,'host':****,'uri': mysql url with username ,password,database}, 
         'db2': {'username': ****, 'hostname': *****,host: ******, 'password': ***,'uri': mysql url with username ,password,database}}

global conn
conn={}
def connect():
 cred=json.loads(os.environ['dict'])
 for db in cred:
   multiple_databases=cred[db]['uri']
   url=urlparse.urlparse(multile_databases)           
   conn[db]={'user':'url.username','password':'url.password','host':'url.hostname','database':'url.path[1:]'}
   cnx = mysql.connector.connect(pool_name = "mypool",
                          pool_size = 3,
                          **conn[db])
connect()

此处的问题是只有一个连接被打开,而且它是用于数据库' db2'。

当我执行相同的代码而不实现池时,两个连接都可以正常/打开。

  for db in cred:
   multiple_databases=cred[db]['uri']
   url=urlparse.urlparse(multile_databases)           
   conn[db]=mysql.connector.connect(user=url.username,password=url.password,host=url.hostname,database=url.path[1:])

问题:实现池时为什么两个连接都没有打开?

1 个答案:

答案 0 :(得分:0)

想出来

def conn1():
 pool_size = 3
ser=json.loads(os.environ['dict'])
for db in ser:
  instance_1=ser[db]['uri']
  url=urlparse.urlparse(instance_1)
  pool[db]=PooledDB(mysql.connector, pool_size, user=url.username, password=url.password, host=url.hostname, database=url.path[1:])
  cnx=[None,]*pool_size
  for i in xrange(0,pool_size):
 cnx[i]=pool[db].connection()
 cursor=cnx[i].cursor()
 cursor.execute('SELECT CONNECTION_ID()')
 print "Cnx %d has ID %d" % (i+1,cursor.fetchone()[0])