python dbhelper(simple orm)
# coding:utf- import pymysql class Field(object):
pass class Expr(object):
def __init__(self, model, kwargs):
self.model = model
# How to deal with a non-dict parameter?
self.params = kwargs.values()
equations = [key + ' = %s' for key in kwargs.keys()]
self.where_expr = 'where ' + ' and '.join(equations) if len(equations) > else '' def update(self, **kwargs):
_keys = []
_params = []
for key, val in kwargs.iteritems():
if val is None or key not in self.model.fields:
continue
_keys.append(key)
_params.append(val)
_params.extend(self.params)
sql = 'update %s set %s %s;' % (
self.model.db_table, ', '.join([key + ' = %s' for key in _keys]), self.where_expr)
return Database.execute(sql, _params) def limit(self, rows, offset=None):
self.where_expr += ' limit %s%s' % (
'%s, ' % offset if offset is not None else '', rows)
return self def select(self):
sql = 'select %s from %s %s;' % (', '.join(self.model.fields.keys()), self.model.db_table, self.where_expr)
for row in Database.execute(sql, self.params).fetchall():
inst = self.model()
for idx, f in enumerate(row):
setattr(inst, self.model.fields.keys()[idx], f)
yield inst def count(self):
sql = 'select count(*) from %s %s;' % (self.model.db_table, self.where_expr)
(row_cnt, ) = Database.execute(sql, self.params).fetchone()
return row_cnt class MetaModel(type):
db_table = None
fields = {} def __init__(cls, name, bases, attrs):
super(MetaModel, cls).__init__(name, bases, attrs)
fields = {}
for key, val in cls.__dict__.iteritems():
if isinstance(val, Field):
fields[key] = val
cls.fields = fields
cls.attrs = attrs class Model(object):
__metaclass__ = MetaModel def save(self):
insert = 'insert ignore into %s(%s) values (%s);' % (
self.db_table, ', '.join(self.__dict__.keys()), ', '.join(['%s'] * len(self.__dict__)))
return Database.execute(insert, self.__dict__.values()) @classmethod
def where(cls, **kwargs):
return Expr(cls, kwargs) class Database(object):
autocommit = True
conn = None
db_config = {} @classmethod
def connect(cls, **db_config):
cls.conn = pymysql.connect(host=db_config.get('host', 'localhost'), port=int(db_config.get('port', )),
user=db_config.get('user', 'root'), passwd=db_config.get('password', ''),
db=db_config.get('database', 'test'), charset=db_config.get('charset', 'utf8'))
cls.conn.autocommit(cls.autocommit)
cls.db_config.update(db_config) @classmethod
def get_conn(cls):
if not cls.conn or not cls.conn.open:
cls.connect(**cls.db_config)
try:
cls.conn.ping()
except pymysql.OperationalError:
cls.connect(**cls.db_config)
return cls.conn @classmethod
def execute(cls, *args):
cursor = cls.get_conn().cursor()
cursor.execute(*args)
return cursor def __del__(self):
if self.conn and self.conn.open:
self.conn.close() def execute_raw_sql(sql, params=None):
return Database.execute(sql, params) if params else Database.execute(sql)
python dbhelper(simple orm)的更多相关文章
- python下的orm基本操作(1)--Mysql下的CRUD简单操作(含源码DEMO)
最近逐渐打算将工作的环境转移到ubuntu下,突然发现对于我来说,这ubuntu对于我这种上上网,收收邮件,写写博客,写写程序的时实在是太合适了,除了刚接触的时候会不怎么完全适应命令行及各种权限管理, ...
- 使用国内镜像通过pip安装python的一些包 Cannot fetch index base URL http://pypi.python.org/simple/
原文地址:http://www.xuebuyuan.com/1157602.html 学习flask,安装virtualenv环境,这些带都ok,但是一安装包总是出错无法安装, 比如这样超时的问题: ...
- python 之路,Day11(上) - python mysql and ORM
python 之路,Day11 - python mysql and ORM 本节内容 数据库介绍 mysql 数据库安装使用 mysql管理 mysql 数据类型 常用mysql命令 创建数据库 ...
- pip安装python包出现Cannot fetch index base URL http://pypi.python.org/simple/
pipinstall***安装python包,出现 Cannot fetch index base URL http://pypi.python.org/simple /错误提示或者直接安装不成功. ...
- 46 Simple Python Exercises-Very simple exercises
46 Simple Python Exercises-Very simple exercises 4.Write a function that takes a character (i.e. a s ...
- python pymysql和orm
pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同. 1. 安装 管理员打开cmd,切换到python的安装路径,进入到Scripts目录下(如:C:\Users\A ...
- python——Django(ORM连表操作)
千呼万唤始出来~~~当当当,终于系统讲了django的ORM操作啦!!!这里记录的是django操作数据库表一对多.多对多的表创建及操作.对于操作,我们只记录连表相关的内容,介绍增加数据和查找数据,因 ...
- python decorator simple example
Why we need the decorator in python ? Let's see a example: #!/usr/bin/python def fun_1(x): return x* ...
- Python-Day12 Python mysql and ORM
一.Mysql数据库 1.什么是数据库? 数据库(Database)是按照数据结构来组织.存储和管理数据的仓库, 每个数据库都有一个或多个不同的API用于创建,访问,管理,搜索和复制所保存的数据 ...
随机推荐
- 为什么Underscore
Underscore是什么? Underscore一个JavaScript实用库,提供了一整套函数式编程的实用功能,但是没有扩展任何JavaScript内置对象.它是这个问题的答案:“如果我在一个空白 ...
- JavaScript事件处理程序 学习笔记
我一直认为Javascript的特点就是在和用户交互的过程中可以进行一些操作,那么事件作为用户交互的主要部分就显得特别重要,今天先学习了JS事件处理程序的相关内容. 首先,要明白Javascript ...
- 实力为王 八年DBA经验谈
首先说说我的经历吧,工作8年,一直是搞运维这一块.做数据库的工作大概6年多,ORACLE DBA大概做了有4年多,目前只能说是比入门级稍高点的水平.我是最近为了换个更好的工作才在今年通过的OCP 11 ...
- 关于ECharts Java类库的一个jquery插件
在项目中开发图表功能时用到了Echars和一个关于Echars的java类库(http://git.oschina.net/free/ECharts).这个类库主要目的是方便在Java中构造EChar ...
- css单位和值
css需要单位来度量.内含整数.小数.百分数的情况,很多条件下支持正负的情况,当然是有限制的了.百分数基本是相对于自身.或是父或是祖先元素的某个属性值. 颜色 颜色的表示分为:命名颜色 ...
- jQuery二级联动
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 转:HTML 5 控件事件属性
Window 事件属性 window 对象触发的事件. 适用于 <body> 标签: 属性 值 描述 onafterprint script 在打印文档之后运行脚本 onbeforepri ...
- jchat:linux聊天程序4:客户端
makefile: jchat: main.o login.o regist.o tcp.o gcc -w main.o login.o regist.o tcp.o -o jchat rm -f * ...
- 用正则表达式抓取网页中的ul 和 li标签中最终的值!
获取你要抓取的页面 const string URL = "http://www.hn3ddf.gov.cn/price/GetList.html?pageno=1& ...
- 在strings.xml中定义html标签
在项目的开发过程中,需要用到把html内容放到strings.xml文件中,然后再读取到TextView中.原本以为像普通文本一样直接SetText就行了,结果行不通,大大超出我的预料.经过网上搜索, ...