用Python方法对Cursor进行扩展。为了方便使用,所以我对MySQLdb的Cursor进行了扩展,使其能够支持带?以及:xxx的查询方式。是因为以下原因。
目前的MySQLdb中的sql的语法,支持如下类型的语法:
insert into users(id, name, domain, created_at)values(%s, %s, %s, %s)
除以上之外,工作也会也用到很多的一些通用的sql的语法,是下面这样的:
insert into users(id, name, domain, created_at)values(?, ?, ?, ?)
python 安装,insert into users(id, name, domain, created_at)values(:id, :name, :domain, :created_at)
class BaseCursor(MySQLdb.cursors.BaseCursor):
def _get_query_parameters(self, query, params):
if isinstance(params, dict) and params:
p = re.compile(':\w+')
return (p.sub('%s', query),
在python中、[params[param_token[1:]] for param_token in p.findall(query)])
else:
return (query.replace('?', '%s'), params)
def execute(self, query, args=None):
(query, params) = self._get_query_parameters(query, args)
return MySQLdb.cursors.BaseCursor.execute(self, query, params)
python 类、class Cursor(CursorStoreResultMixIn, CursorTupleRowsMixIn,
BaseCursor):
#www.iplaypy.com
#调用的代码如下:
cursor=Cursor(self._dbconn)
try:
python和java、cursor.execute('insert into users(name, domain)values(:name, :domain)', dict(name='xxx', domain='hahaha'))
return cursor.lastrowid
finally:
cursor.close()
玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/code/other/o2457.html
相关文章 Recommend
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态