python连接池存在的问题_python 数据库连接池的坑

因需要变化需要改造以前的数据库,整理数据库的时候用python写脚本来洗数据,由于刚刚接触python不久,就像网上找个数据库连接池,于是找到了DBUtils,根据网上的代码直接跑了一遍,跑的时候是查询,没什么问题;然后我就开始用到项目上,结果提示插入数据成功,但数据库却没有变化,折腾了很久,最后试试有没有数据库事务,就调用了一个提交的方法,居然有效;由于类中没有注明,莫名奇妙的踩坑了。

代码如下:

# -*- coding: UTF-8 -*-

"""

Created on 2016年5月7日

@author: baocheng

1、执行带参数的SQL时,请先用sql语句指定需要输入的条件列表,然后再用tuple/list进行条件批配

2、在格式SQL中不需要使用引号指定数据类型,系统会根据输入参数自动识别

3、在输入的值中不需要使用转意函数,系统会自动处理

"""

import MySQLdb

from MySQLdb.cursors import DictCursor

from DBUtils.PooledDB import PooledDB

# from PooledDB import PooledDB

import DbConfig

"""

Config是一些数据库的配置文件

"""

class Mysql(object):

"""

MYSQL数据库对象,负责产生数据库连接 , 此类中的连接采用连接池实现获取连接对象:conn = Mysql.getConn()

释放连接对象;conn.close()或del conn

"""

# 连接池对象

__pool = None

def __init__(self):

# 数据库构造函数,从连接池中取出连接,并生成操作游标

self._conn = Mysql.__getConn()

self._cursor = self._conn.cursor()

@staticmethod

def __getConn():

"""

@summary: 静态方法,从连接池中取出连接

@return MySQLdb.connection

"""

if Mysql.__pool is None:

__pool = PooledDB(creator=MySQLdb, mincached=1, maxcached=20,

host=DbConfig.DBHOST, port=DbConfig.DBPORT, user=DbConfig.DBUSER, passwd=DbConfig.DBPWD,

db=DbConfig.DBNAME, use_unicode=False, charset=DbConfig.DBCHAR, cursorclass=DictCursor)

return __pool.connection()

def getAll(self, sql, param=None):

"""

@summary: 执行查询,并取出所有结果集

@param sql:查询SQL,如果有查询条件,请只指定条件列表,并将条件值使用参数[param]传递进来

@param param: 可选参数,条件列表值(元组/列表)

@return: result list(字典对象)/boolean 查询到的结果集

"""

if param is None:

count = self._cursor.execute(sql)

else:

count = self._cursor.execute(sql, param)

if count > 0:

result = self._cursor.fetchall()

else:

result = False

return result

def getOne(self, sql, param=None):

"""

@summary: 执行查询,并取出第一条

@param sql:查询SQL,如果有查询条件,请只指定条件列表,并将条件值使用参数[param]传递进来

@param param: 可选参数,条件列表值(元组/列表)

@return: result list/boolean 查询到的结果集

"""

if param is None:

count = self._cursor.execute(sql)

else:

count = self._cursor.execute(sql, param)

if count > 0:

result = self._cursor.fetchone()

else:

result = False

return result

def getMany(self, sql, num, param=None):

"""

@summary: 执行查询,并取出num条结果

@param sql:查询SQL,如果有查询条件,请只指定条件列表,并将条件值使用参数[param]传递进来

@param num:取得的结果条数

@param param: 可选参数,条件列表值(元组/列表)

@return: result list/boolean 查询到的结果集

"""

if param is None:

count = self._cursor.execute(sql)

else:

count = self._cursor.execute(sql, param)

if count > 0:

result = self._cursor.fetchmany(num)

else:

result = False

return result

def insertOne(self, sql, value):

"""

@summary: 向数据表插入一条记录

@param sql:要插入的SQL格式

@param value:要插入的记录数据tuple/list

@return: insertId 受影响的行数

"""

self._cursor.execute(sql, value)

return self.__getInsertId()

def insertMany(self, sql, values):

"""

@summary: 向数据表插入多条记录

@param sql:要插入的SQL格式

@param values:要插入的记录数据tuple(tuple)/list[list]

@return: count 受影响的行数

"""

count = self._cursor.executemany(sql, values)

return count

def __getInsertId(self):

"""

获取当前连接最后一次插入操作生成的id,如果没有则为0

"""

self._cursor.execute("SELECT @@IDENTITY AS id")

result = self._cursor.fetchall()

return result[0]['id']

def __query(self, sql, param=None):

if param is None:

count = self._cursor.execute(sql)

else:

count = self._cursor.execute(sql, param)

return count

def update(self, sql, param=None):

"""

@summary: 更新数据表记录

@param sql: SQL格式及条件,使用(%s,%s)

@param param: 要更新的 值 tuple/list

@return: count 受影响的行数

"""

return self.__query(sql, param)

def delete(self, sql, param=None):

"""

@summary: 删除数据表记录

@param sql: SQL格式及条件,使用(%s,%s)

@param param: 要删除的条件 值 tuple/list

@return: count 受影响的行数

"""

return self.__query(sql, param)

def begin(self):

"""

@summary: 开启事务

"""

self._conn.autocommit(0)

def end(self, option='commit'):

"""

@summary: 结束事务

"""

if option == 'commit':

self._conn.commit()

else:

self._conn.rollback()

def dispose(self, isEnd=1):

"""

@summary: 释放连接池资源

"""

if isEnd == 1:

self.end('commit')

else:

self.end('rollback');

self._cursor.close()

self._conn.close()

数据库配置文件 DbConfig

# coding:utf-8

'''

Created on 2016年5月7日

@author: baocheng

'''

DBHOST = "192.168.2.200"

DBPORT = 3306

DBUSER = "test"

DBPWD = "test"

DBNAME = "test"

DBCHAR = "utf8"

测试代码

# coding:utf-8

'''

@author: baocheng

'''

from MySqlConn import Mysql

from _sqlite3 import Row

# 申请资源

mysql = Mysql()

sqlAll = "select userid,name from t_user order by userid desc limit 11"

result = mysql.getAll(sqlAll)

if result:

print "get all"

for row in result:

print "%s\t%s" % (row["userid"], row["name"])

"""insert """

#占位符用%s

sqlSave = "INSERT INTO t_test(userid)' values(%s) "

'''参数使用tuple或list'''

data = ['11111111']

'''执行插入操作'''

mysql.insertOne(sqlSave,data)

'''commit 操作,并关闭连接池'''

mysql.dispose()

参考博客:http://blog.csdn.net/zbc1090549839/article/details/51336458

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
个步骤: 1. 找到链表尾部节点的前一个节点。 ```c struct Node* prevNode = *head; while (prevNode->next->next != NULL) { prevNode = prevNode->next; } ``` 2. 找到SQLAlchemy是一个流行的Python ORM框架,它提供了一个灵活的数据库连接池连接池是一种链表尾部节点。 ```c struct Node* delNode = prevNode->next; ``` 3. 将前一个节点的技术,它可以提高数据库操作的性能和可靠性。它通过维护一定数量的数据库连接来避免频繁地打开和关闭数据库连接,从而提高效率。 下面是SQLAlchemy连接池的一些原指针域设置为`NULL`。 ```c prevNode->next = NULL; ``` 4. 释放被删除节点理说明: 1. SQLAlchemy连接池是基于Python标准库中的Queue模块实现的。连接池是一个队的内存空间。 ```c free(delNode); ``` 完整代码如下: ```c void deleteAtTail(struct列,其中每个元素都是一个数据库连接对象。 2. 当客户端请求一个数据库连接时,连接池会 Node** head) { if (*head == NULL) { return; } if ((*head)->next == NULL) { 从队列中获取一个空闲连接对象。如果队列为空,连接池会创建一个新的连接对象,并将其加 free(*head); *head = NULL; return; } struct Node* prevNode = *head; while (prev入队列。 3. 客户端使用完连接对象后,必须将其还回连接池中。连接池会将Node->next->next != NULL) { prevNode = prevNode->next; } struct Node* delNode = prevNode连接对象标记为可用,然后将其放回队列中。 4. 如果连接池中的连接对象数量超->next; prevNode->next = NULL; free(delNode); } ``` ## 5. 动态链表的修改过了设定的上限,连接池会将多余的连接对象关闭,以避免资源浪费。 5. SQLAlchemy连接池还提供了一些高级功能,比如连接池中连接对象的自动重连、超时控制 动态链表的修改操作需要完成以下几个步骤: 1. 找到待修改节点。 ```c struct Node、连接对象状态检查等。 总之,SQLAlchemy连接池是一种非常有用的技术,可以提高* currNode = *head; while (currNode != NULL && currNode->data != oldData) { currNode = currNode数据库操作的性能和可靠性。它可以避免频繁地打开和关闭数据库连接,从而节省资源和时间。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值