torndb是tornado框架封装使用MySQLdb,十分方便。
class Connection(object):
def __init__(self, host, database, user=None, password=None,
max_idle_time=7 * 3600, connect_timeout=0,
time_zone="+0:00", charset = "utf8", sql_mode="TRADITIONAL"):
self.host = host
self.database = database
self.max_idle_time = float(max_idle_time)
参数
在这里,可以学到几种参数的传输
*;一个星号代表的是tuple,元组
**;双星号代表的是字典
还有一种user=None,是为了防止没有这个参数
初始化
host:主机号
database:数据库名
user=None
password=None
charset:utf-8 编码
time_zone:时区
max_idle_time:最大空闲时间,默认为7个小时
connect_timeout
sql_mode:
self.host = host
self.database = database
self.max_idle_time = float(max_idle_time)
args = dict(conv=CONVERSIONS, use_unicode=True, charset=charset,
db=database, init_command=('SET time_zone = "%s"' % time_zone),
connect_timeout=connect_timeout, sql_mode=sql_mode)
使用dict()生成一个字典:他的作用现在也不知道
if user is not None:
args["user"] = user
if password is not None:
args["passwd"] = password
如果用户,密码存在,就加到args字典中去
# We accept a path to a MySQL socket file or a host(:port) string
if "/" in host:
args["unix_socket"] = host
else:
self.socket = None
pair = host.split(":")
if len(pair) == 2:
args["host"] = pair[0]
args["port"] = int(pair[1])
else:
args["host"] = host
args["port"] = 3306
“/”和“\”
windows下是\,linux和unix下是/
self._db = None
self._db_args = args
self._last_use_time = time.time()
self._last_use_time = time.time()
算的是1970年1月1日至今的时间秒数
self._db = None:置为空,这个是MySQLdb连接的db
try:
self.reconnect()
except Exception:
logging.error("Cannot connect to MySQL on %s", self.host,
exc_info=True)
reconnect
这里调用self.reconnect()方法,那就看看他是干嘛的
def reconnect(self):
"""Closes the existing database connection and re-opens it."""
self.close()
self._db = MySQLdb.connect(**self._db_args)
self._db.autocommit(True)
关闭存在的数据库连接,然后重新连接他
self._db = MySQLdb.connect(**self._db_args) MySQLdb的连接
self._db.autocommit(True)
autocommit属性设置为True:这样设置的作用是自动提交
close 关闭数据库的连接
def close(self):
"""Closes this database connection."""
if getattr(self, "_db", None) is not None:
self._db.close()
self._db = None
获取对象(自己本身)的“_db”属性是不是None,不是的话,就关闭,并且置为None
def __del__(self):
self.close()
python 类的__del__方法
__del__方法
当一个类实例删除时被调用
query方法
def query(self, query, *parameters, **kwparameters):
"""Returns a row list for the given query and parameters."""
cursor = self._cursor()
try:
self._execute(cursor, query, parameters, kwparameters)
if cursor.description:
column_names = [d[0] for d in cursor.description]
return [Row(itertools.izip(column_names, row)) for row in cursor]
return None
finally:
cursor.close()
_cursor方法:cursor的意思是数据库中的游标,一种查询方法
确保数据库连接,然后MySQLdb获取游标:相当于db.cursor()
def _cursor(self):
self._ensure_connected()
return self._db.cursor()
确保连接:
def _ensure_connected(self):
# Mysql by default closes client connections that are idle for
# 8 hours, but the client library does not report this fact until
# you try to perform a query and it fails. Protect against this
# case by preemptively closing and reopening the connection
# if it has been idle for too long (7 hours by default).
if (self._db is None or
(time.time() - self._last_use_time > self.max_idle_time)):
self.reconnect()
self._last_use_time = time.time()
如果db没有,而且时间大于最大空闲时间,重新连接数据库
_execute方法
def _execute(self, cursor, query, parameters, kwparameters):
# try:
# return cursor.execute(query, kwparameters or parameters)
try:
return cursor.execute(query, kwparameters or parameters)
except ProgrammingError:
self.close()
return None
except OperationalError:
logging.error("Error connecting to MySQL on %s", self.host)
self.close()
raise
执行MySQLdb的execute方法,
假如发生