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用于创建,访问,管理,搜索和复制所保存的数据 ...
随机推荐
- 【floyed】【HDU1217】【Arbitrage】
题目大意: 给你几种货币,以及几种汇率关系,问是否存在套利的可能? 思路: 初步想法:图上存在一个环的路径上权值相乘大于1.... 再者:该如何找到图上所有环呢.... 好吧 经过鸟神 和 况神的指点 ...
- jQuery基础---Ajax基础教程(二)
jQuery基础---Ajax进阶 内容提纲: 1.加载请求 2.错误处理 3.请求全局事件 4.JSON 和 JSONP 5.jqXHR 对象 发文不易,转载请注明出处! 在 Ajax 基础一篇中, ...
- js callback函数
A callback is a function that is passed as an argument to another function and is executed after its ...
- 2015.01.06 JQuery
jQuery是一个兼容多浏览器的javascript库.开发出来的JavaScript的脚本包.非侵入性的脚本. 下载地址:http://jquery.com/ (打不开网页需要翻* ...
- IBATIS处理typeHandler类容易范的SQLException总结
1. java.sql.SQLException: 无效的列类型 原因: A. ibatis的IN,OUT参数.或者typeHandler类中传入的参数值数据类型与Oracle自定义对象中的属性值的数 ...
- Excel转JSON-简单-暴力-迅速
一直在做一个关于网上选课的系统,选用了时下比较流行的node.js.今天在想怎么把学生或者老师的信息导入进去,涉及数量比较多一点,我手边又正好有一部分excel的表格.就想把excel转成json然后 ...
- 转载 java枚举类型enum的使用 (原文地址:http://blog.csdn.net/wgw335363240/article/details/6359614)
java枚举类型enum的使用 最近跟同事讨论问题的时候,突然同事提到我们为什么java中定义的常量值不采用enmu枚举类型,而采用public final static 类型来定义呢?以前我们都是采 ...
- php设计模式笔记--总结篇
一.引入 设计模式的一般定义不再说,只大概说一下我理解的设计模式,我理解的设计模式的主要目的是利用面向对象(类.接口等)特点,让代码更加易于扩展,易于重用,易于维护.这三个特点也就要求我们不要将太多 ...
- Java-Poi 读取excel 数据
一直想着使用java操作excel,但有时各种原因一直没有实现.由于工作无意间做了个其他demo,为了进一步发散就涉及到了使用excel,为此开始正式接触POI,虽然限制不是很了解POI,但是通过查阅 ...
- Python学习笔记--Python字符串连接方法总结
声明: 这些总结的学习笔记,一部分是自己在工作学习中总结,一部分是收集网络中的知识点总结而成的,但不到原文链接.如果有侵权,请知会,多谢. python中有很多字符串连接方式,总结一下: 1)最原始的 ...