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用于创建,访问,管理,搜索和复制所保存的数据 ...
随机推荐
- Bctf-pwn_ruin-re_lastflower
Pwn-ruin 用几个词来概括下漏洞原理:Arm+heap overflow(house of force)+dl-resolve Info leak: 在printf key8时,泄漏堆上地址(s ...
- Windows下nc文件传输
起初用的一下命令: 接收端:nc –n –l –p port –vv > xxx 发送端:nc –n ip port < yyy 但是发现数据传输完成后,不会自动断开连接,要手动的断开,这 ...
- MySQL之终端(Terminal)管理数据库、数据表、数据的基本操作(转)
MySQL有很多的可视化管理工具,比如“mysql-workbench”和“sequel-pro-”. 现在我写MySQL的终端命令操作的文章,是想强化一下自己对于MySQL的理解,总会比使用图形化的 ...
- 浏览器的重绘(repaints)与重排(reflows)
转:http://www.css88.com/archives/4991#more-4991 在项目的交互或视觉评审中,前端同学常常会对一些交互效果质疑,提出这样做不好那样做不好.主要原因是这些效果通 ...
- SQL Server中调用WebService的实例
尊重原著作:本文转载自http://www.cnblogs.com/icycore/p/3532197.html 1.Ole Automation Procedures 服务器配置选项 当启用 OLE ...
- 与时间有关的windows函数
(一)time_t time(time_t *t) 如果t是空指针,直接返回当前时间.如果t不是空指针,返回当前时间的同时,将返回值赋予t指向的内存空间. 这个函数的返回值,是指自 Unix 纪元(J ...
- C语言_double_精度的谜团
double-long long 和0的比较,double和double之间比较
- python基础:列表生成式和生成器
列表生成式(List Comprehension) 列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式. 举个例子,要生成 list ...
- 【转载】Java线程面试题 Top 50
Java线程面试题 Top 50 2014/08/21 | 分类: 基础技术 | 4 条评论 | 标签: 多线程, 面试题 分享到:140 本文由 ImportNew - 李 广 翻译自 javare ...
- 原生JS研究:学习jquery源码,收集整理常用JS函数
原生JS研究:学习jquery源码,收集整理常用JS函数: 1. JS获取原生class(getElementsByClass) 转自:http://blog.csdn.net/kongjiea/ar ...