MySQL默认一个连接超过8小时无操作就断开该连接,对于想要长期保持连接的应用场景而言,太不方便
Python的MySQL绑定MySQLdb
发现DBUtils是一个不错的Python连接池 工具,根据这篇文章的代码,运行条SQL insert语句,发现有unicode错误
'latin-1' codec can't encode characters in position 97-99: ordinal not in range(256)
此时需要将原文的连接池构建语句改成
pool = PooledDB(MySQLdb,15,host='localhost',user='test',passwd='test',db='crawl',port=3306, charset="utf8") #15为连接池里的最少连接数
即 多添加 一个参数charset,就能解决unicode错误
其实,从host开始的所有参数,都不是DBUtils关心的,而是透传给MySQLdb这个数据库python绑定接口,怎么透传呢?看PooledDB类的构造函数
| __init__(self, creator, mincached=0, maxcached=0, maxshared=0, maxconnections=0, blocking=False, maxusage=None, setsession=None, reset=True, failures=None, ping=1, *args, **kwargs)
| Set up the DB-API 2 connection pool.
|
| creator: either an arbitrary function returning new DB-API 2
| connection objects or a DB-API 2 compliant database module
| mincached: initial number of idle connections in the pool
| (0 means no connections are made at startup)
| maxcached: maximum number of idle connections in the pool
| (0 or None means unlimited pool size)
| maxshared: maximum number of shared connections
| (0 or None means all connections are dedicated)
| When this maximum number is reached, connections are
| shared if they have been requested as shareable.
| maxconnections: maximum number of connections generally allowed
| (0 or None means an arbitrary number of connections)
| blocking: determines behavior when exceeding the maximum
| (if this is set to true, block and wait until the number of
| connections decreases, otherwise an error will be reported)
| maxusage: maximum number of reuses of a single connection
| (0 or None means unlimited reuse)
| When this maximum usage number of the connection is reached,
| the connection is automatically reset (closed and reopened).
| setsession: optional list of SQL commands that may serve to prepare
| the session, e.g. ["set datestyle to ...", "set time zone ..."]
| reset: how connections should be reset when returned to the pool
| (False or None to rollback transcations started with begin(),
| True to always issue a rollback for safety's sake)
| failures: an optional exception class or a tuple of exception classes
| for which the connection failover mechanism shall be applied,
| if the default (OperationalError, InternalError) is not adequate
| ping: determines when the connection should be checked with ping()
| (0 = None = never, 1 = default = whenever fetched from the pool,
| 2 = when a cursor is created, 4 = when a query is executed,
| 7 = always, and all other bit combinations of these values)
| args, kwargs: the parameters that shall be passed to the creator
| function or the connection constructor of the DB-API 2 module
是通过最后2个参数,*args和**kwargs,来透传的
*args和**kwargs分别代表tuple参数和dict参数,但这种方式 比 显式指定tuple和dict两个位置参数 要好,因为少了一层 封装
关于*args和**kwargs的进一步信息,可以参考这篇文章