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用于创建,访问,管理,搜索和复制所保存的数据 ...
随机推荐
- GrideView合并列合并序号,隐藏某列按钮
合并编号列 /// <summary> /// 合并GridView中某列相同信息的行(单元格) /// </summary> /// <param name=" ...
- MS sqlserver 获取某月某年的天数
--定义传入时间 ) set @datetime='2012-02-01' --定义月的天数 declare @dayCountM int --定义年的天数 declare @dayCountY in ...
- 各版本SDK Tools及ADT下载技巧
我们在开发的时候,尤其是使用Eclipse安装ADT插件进行环境配置,我们需要从下载ADT插件及SDK,当我们从官网下载的时候,有的时候可能找不到下载的地方或者下载不到自己想要的版本,我就在此总结下如 ...
- poj3292-类素数筛选法
#include<iostream>using namespace std;const int N=1000002;int array[N]={0};int main(){ int n; ...
- WireShark抓包软件的使用
在大学的时候学习的计算机网络的具体的知识,也使用过wireshark去抓取一些网络的封包用来分析,但是都没能系统的写一篇博客,今天总结一下吧. wireshark介绍 wireshark的官方下载网站 ...
- js返回当前时间的毫秒数
Date.now(); +new Date(); new Date().getTime();
- CC++初学者编程教程(5) 安装codeblocks软件开发环境
Code::Blocks 是一个开放源码的全功能的跨平台C/C++集成开发环境. Code::Blocks是开放源码软件.Code::Blocks由纯粹的C++语言开发完成,它使用了蓍名的图形界面库w ...
- POJ 3662 Telephone Lines(二分答案+SPFA)
[题目链接] http://poj.org/problem?id=3662 [题目大意] 给出点,给出两点之间连线的长度,有k次免费连线, 要求从起点连到终点,所用的费用为免费连线外的最长的长度. 求 ...
- Spring、Bean 的作用域
Singleton作用域(默认) 当一个bean的作用域为singleton,那么Spring Ioc容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则 ...
- uva 193 Graph Coloring(图染色 dfs回溯)
Description You are to write a program that tries to find an optimal coloring for a given graph. Col ...