1.版本1:初始化

# -*- coding:utf-8 -*-
from MySQLdb import * class MysqlHelper:
def __init__(self,host,port,user,passwd,db,charset='utf8'):
self.host=host
self.port=port
self.user=user
self.passwd=passwd
self.db=db
self.charset=charset mysql1 = MysqlHelper("localhost",3306,"root","mysql","py31""utf8")

2.版本2:打开关闭方法

# -*- coding:utf-8 -*-
from MySQLdb import * class MysqlHelper:
"""封装"""
def __init__(self,host,port,user,passwd,db,charset='utf8'):
"""初始化"""
self.host=host
self.port=port
self.user=user
self.passwd=passwd
self.db=db
self.charset=charset def open(self):
"""连接数据库"""
self.conn = connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db, charset=self.charset)
self.cursor1 = self.conn.cursor() def close(self):
"""关闭连接"""
self.cursor1.close()
self.conn.close() mysql1 = MysqlHelper("localhost",3306,"root","mysql","py31""utf8")

3.版本3:增加修改删除

# -*- coding:utf-8 -*-
from MySQLdb import * class MysqlHelper:
"""封装"""
def __init__(self,host,port,user,passwd,db,charset='utf8'):
"""初始化"""
self.host=host
self.port=port
self.user=user
self.passwd=passwd
self.db=db
self.charset=charset def open(self):
"""连接数据库"""
self.conn = connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db, charset=self.charset)
self.cursor1 = self.conn.cursor() def close(self):
"""关闭连接"""
self.cursor1.close()
self.conn.close() def iud(self,sql_content):
"""增删改"""
self.open() #调用open方法 self.sql = '%s'[sql_content]
self.cursor1.execute(self.sql)
self.conn.commit() self.close() #调用close方法 mysql1 = MysqlHelper("localhost",3306,"root","mysql","py31""utf8") sql_content = raw_input('请输入sql语句:')
mysql1.iud(sql_content)

      

4.版本4:抛出异常,参数化

# -*- coding:utf-8 -*-
from MySQLdb import * class MysqlHelper:
"""封装"""
def __init__(self,host,port,user,passwd,db,charset='utf8'):
"""初始化"""
self.host=host
self.port=port
self.user=user
self.passwd=passwd
self.db=db
self.charset=charset def open(self):
"""连接数据库"""
self.conn = connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db, charset=self.charset)
self.cursor1 = self.conn.cursor() def close(self):
"""关闭连接"""
self.cursor1.close()
self.conn.close() def iud(self,sql,params):
"""增删改"""
try:
self.open() #调用open方法 self.cursor1.execute(sql,params)
self.conn.commit() self.close() #调用close方法
print('ok')
except Exception as e:
print(e.message) mysql1 = MysqlHelper("localhost",3306,"root","mysql","py31","utf8") name = "jack"
id = 1
sql = 'update students set name=%s where id=%s'
params=[name,id]
mysql1.iud(sql,params)
/usr/bin/python2.7 /home/python/code/03-class封装.py
ok +----+------------+--------+---------------------+----------+
| 1 | jack | | 1999-09-09 00:00:00 | |

5.版本5:查询

# -*- coding:utf-8 -*-
from MySQLdb import * class MysqlHelper:
"""封装"""
def __init__(self,host,port,user,passwd,db,charset='utf8'):
"""初始化"""
self.host=host
self.port=port
self.user=user
self.passwd=passwd
self.db=db
self.charset=charset def open(self):
"""连接数据库"""
self.conn = connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db, charset=self.charset)
self.cursor1 = self.conn.cursor() def close(self):
"""关闭连接"""
self.cursor1.close()
self.conn.close() def iud(self,sql,params):
"""增删改"""
try:
self.open() #调用open方法 self.cursor1.execute(sql,params)
self.conn.commit() self.close() #调用close方法
print('ok')
except Exception as e:
print(e.message) def all(self,sql,params=()): #默认参数
try:
self.open()
print ""
self.cursor1.execute(sql,params)
result = self.cursor1.fetchall() #fetchall()获取多条数据
print "" #fetchone()获取1条数据
print(result)
self.close() return result #返回result except Exception as e:
print(e.message) mysql1 = MysqlHelper("localhost",3306,"root","mysql","py31","utf8") sql = 'select * from students where id<5'
result = mysql1.all(sql)
print(result)
1
2
((1L, u'jack', '\x01', datetime.datetime(1999, 9, 9, 0, 0), '\x00'), (2L, u'\u817e\u65ed', '\x01', datetime.datetime(1990, 2, 2, 0, 0), '\x00'), (3L, u'\u7f51\u6613', '\x01', None, '\x00'), (4L, u'\u5c0f\u7c73', '\x01', None, '\x00'))
((1L, u'jack', '\x01', datetime.datetime(1999, 9, 9, 0, 0), '\x00'), (2L, u'\u817e\u65ed', '\x01', datetime.datetime(1990, 2, 2, 0, 0), '\x00'), (3L, u'\u7f51\u6613', '\x01', None, '\x00'), (4L, u'\u5c0f\u7c73', '\x01', None, '\x00'))

6.版本6:获取单条数据

# -*- coding:utf-8 -*-
from MySQLdb import * class MysqlHelper:
"""封装"""
def __init__(self,host,port,user,passwd,db,charset='utf8'):
"""初始化"""
self.host=host
self.port=port
self.user=user
self.passwd=passwd
self.db=db
self.charset=charset def open(self):
"""连接数据库"""
self.conn = connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db, charset=self.charset)
self.cursor1 = self.conn.cursor() def close(self):
"""关闭连接"""
self.cursor1.close()
self.conn.close() def iud(self,sql,params):
"""增删改"""
try:
self.open() #调用open方法 self.cursor1.execute(sql,params)
self.conn.commit() self.close() #调用close方法
print('ok')
except Exception as e:
print(e.message) def all(self,sql,params=()):
"""获取多条数据"""
try:
self.open() self.cursor1.execute(sql,params)
result = self.cursor1.fetchall()
print(result) self.close() return result except Exception as e:
print(e.message) def one(self,sql,params=()):
"""获取单挑数据"""
try:
self.open() self.cursor1.execute(sql,params)
result = self.cursor1.fetchone()
print(result) self.close() return result except Exception as e:
print(e.message)

7.版本7:封装完成

#encoding=utf8
import MySQLdb class MysqlHelper():
def __init__(self,host,port,db,user,passwd,charset='utf8'):
self.host=host
self.port=port
self.db=db
self.user=user
self.passwd=passwd
self.charset=charset def connect(self):
self.conn=MySQLdb.connect(host=self.host,port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset)
self.cursor=self.conn.cursor() def close(self):
self.cursor.close()
self.conn.close() def get_one(self,sql,params=()):
result=None
try:
self.connect()
self.cursor.execute(sql, params)
result = self.cursor.fetchone()
self.close()
except Exception, e:
print e.message
return result def get_all(self,sql,params=()):
list=()
try:
self.connect()
self.cursor.execute(sql,params)
list=self.cursor.fetchall()
self.close()
except Exception,e:
print e.message
return list def insert(self,sql,params=()):
return self.__edit(sql,params) def update(self, sql, params=()):
return self.__edit(sql, params) def delete(self, sql, params=()):
return self.__edit(sql, params) def __edit(self,sql,params):
count=0
try:
self.connect()
count=self.cursor.execute(sql,params)
self.conn.commit()
self.close()
except Exception,e:
print e.message
return count

8 当做第三方模块导入

    

10 class封装 ORM的更多相关文章

  1. Windows XP/Windows 7/Windows 8/Windows 10系统封装的另类教程和思路

    如果是早些年,XP时代的Ghost封装,各种的封装工具和驱动只能安装工具满天飞,比如龙帝国,还有很早用C++写的忘了什么名字了,自由天空的,非常的多: 当时为什么要用Ghost和用这些驱动安装工具以及 ...

  2. 10 python 封装----@property的用法

    1.基本概念 在python中用双下划线开头的方式将属性隐藏起来(设置成私有的) #其实这仅仅这是一种变形操作 #类中所有双下划线开头的名称如__x都会自动变形成:_类名__x的形式: class A ...

  3. 封装ORM.py与mysql_client.py代码

    ORM.py ''' ORM: 对象关系映射 ---> 映射到数据库MySQL中的数据表 类名 ---> 表名 对象 ---> 一条记录 对象.属性 ---> 字段 模拟Dja ...

  4. 我的第一个python web开发框架(30)——定制ORM(六)

    在开发中,查询操作是使用最多的,而查询列表是其中之一,查询列表可分为分页查询和不分页查询(它们之间多了一次总记录数查询),还可以分为单表查询和多表关联查询,返回的结构体根据前端使用的表单框架不同而有所 ...

  5. Django中ORM介绍和字段及字段参数

    Object Relational Mapping(ORM) 1 ORM介绍 1.1 ORM概念 对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对 ...

  6. .Net Core3.1 + EF Core + LayUI 封装的MVC版后台管理系统

    项目名称:学生信息管理系统1.0 后台框架:.Net Core 3.1 + EF Core    yrjw.ORM.Chimp 前端框架:ASP.NET Core MVC  +  LayUI + Bo ...

  7. Django基础四之测试环境和ORM查询

    Django基础四之测试环境和ORM查询 目录 Django基础四之测试环境和ORM查询 1. 搭建测试环境 1.1 测试环境搭建方法: 1.2 使用测试环境对数据库进行CURD 1.3 返回Quer ...

  8. 【ASP.NET程序员福利】打造一款人见人爱的ORM(二)

    上一篇我已经给大家介绍AntORM的框架[ASP.NET程序员福利]打造一款人见人爱的ORM(一),今天就来着重介绍一下如何使用这套框架 1>AntORM 所有成员 如果你只想操作一种数据库,可 ...

  9. Moon.Orm 5.0 (MQL版)

    Moon.Orm 5.0 (MQL版) 实战实例Moon.Orm 5.0 革命性的设计 打造最便捷的异步分页技术(提供下载) 摘要: 一.建一个项目(以WebForm为例)配置文件配置(注意您自己的路 ...

随机推荐

  1. mvc中尽量避免使用HttpContext.Current.Request

    在Mvc开发中滥用HttpContext.Current.Request,可能会造成非IE浏览器重复加载页面的情况. 不管你信不,反正我在Mvc3.0中遇到过.

  2. 一次ddos攻击

    公司lvs的vip受到攻击,表现现象为: 1)vip所有服务器没有什么连接,大量的无效connection 2)网卡流量很大 停用vip,流量下降,临时解决攻击问题.但是这只是治标不治本,如果攻击方变 ...

  3. MySQL子查询有哪五种形式?

    MySQL是一个关系型数据库管理系统,由瑞典MySQLAB公司开发,目前属于Oracle旗下产品.MySQL是最流行的关系型数据库管理系统之一,在web应用方面,MySQL是最好的RDBMS(Rela ...

  4. *1 Two Sum two pointers(hashmap one scan)

    Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...

  5. 解决SD卡频繁读写问题 Anything-sync-daemon 映射linux目录到tmpfs并定时同步

    Anything-sync-daemon (asd) is a is a diminutive pseudo-daemon designed to manage target directories ...

  6. react及flux架构范例Todomvc分析

    react及flux架构范例Todomvc分析 通过分析flux-todomvc源码,学习如何通过react构建web程序,了解编写react应用程序的一般步骤,同时掌握Flux的单向数据流动架构思想 ...

  7. mmap内存映射

    http://blog.csdn.net/kongdefei5000/article/details/70183119 内存映射是个很有用,也很有意思的思想.我们都知道操作系统分为用户态和内核态,用户 ...

  8. spring依赖注入(转)

    转自:https://blog.csdn.net/taijianyu/article/details/2338311/ Spring 能有效地组织J2EE应用各层的对象.不管是控 制层的Action对 ...

  9. (python)剑指Offer:数组中重复的数字

    问题描述 在长度为n的数组中,所有的元素都是0到n-1的范围内. 数组中的某些数字是重复的,但不知道有几个重复的数字,也不知道重复了几次,请找出任意重复的数字. 例如,输入长度为7的数组{2,3,1, ...

  10. GPU和CPU耗时统计方法

    GPU端耗时统计 cudaEvent_t start, stop; checkCudaErrors(cudaEventCreate(&start)); checkCudaErrors(cuda ...