在Python数据库连接池中如何创建请求连接的方案


在Python数据库连接池中操作过程中如果你设置好了连接池,你就可以按照如下进行操作。通过以下的内容你就可以轻松的运用Python数据库连接池的相关步骤,希望下面的文章会对你有所收获。

请求连接:

  1. db = pool.connection() 

你可以使用这些连接有如原始的DB-API 2一样。而实际使用的是``SteadyDB``版本的强硬连接。请注意连接可以与其他线程共享,只要你设置 maxshared 参数为非零,并且DB-API 2模块也允许。如果你想要使用专用连接则使用:

  1. db = pool.connection(0) 

如果你不再需要这个连接了,则可以返回给连接池使用 db.close() 。你也可以使用相同的方法获取另一个连接。警告: 在一个多线程环境,不要使用下面的方法:

  1. pool.connection().cursor().execute(...)  
  2. db = pool.connection()  
  3. cur = db.cursor()  
  4. cur.execute(...)  
  5. res = cur.fetchone()  
  6. cur.close() # or del cur  
  7. db.close() # or del db 

示例 [方便你将来直接使用]

使用PersistentDB 模块

  1. import threading,time,datetime  
  2. import MySQLdb  
  3. import DBUtils.PersistentDB  
  4. persist = DBUtils.PersistentDB.PersistentDB(MySQLdb,100,host='localhost',user='root',passwd='321',db='test',charset='utf8')  
  5. conn = persist.connection()  
  6. cursor = conn.cursor()  
  7. cursor.execute("insert into me values(1,'22222')")  
  8. conn.commit()  
  9. conn.close()   

通过以上的内容你就可以得到数据库连接了!

评论关闭