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. ansible使用2-命令

    并发与shell # bruce用户身份,-m指定模块名称,默认模块名command,all所有目标主机,也可以指定组名或者主机名 ansible all -m ping -u bruce # bru ...

  2. Office加载项安装

    出自我的个人主页 Alvin Blog 前言 Excel加载项离不开安装,Excel加载项本身安装及其简单,但这是在申请下来Office开发者账户之后,再次之前都得自行安装 线上安装 微软申请开发者账 ...

  3. Python基础学习之文件(2)

    文件内建方法 1.输入 read()方法用来直接读取字节到字符串中,最多读取给定数目个字节.如果没有给定size参数(默认值为-1)或size值为负,文件将被读取直至末尾. readline()方法读 ...

  4. MySQL的四种主要存储引擎

    在数据库中存的就是一张张有着千丝万缕关系的表,所以表设计的好坏,将直接影响着整个数据库.而在设计表的时候,我们都会关注一个问题,使用什么存储引擎.等一下,存储引擎?什么是存储引擎? 什么是存储引擎? ...

  5. PHP:如果正确加载js、css、images等静态文件

    日常中,我们想要把一些静态页面放在框架上或者是进行转移时,那么静态页面上的原url加载js.css.images都会失效,那么我们应该怎么进行修改捏? 现在仓鼠做个笔记哈 这里有几个注意项: 1.路径 ...

  6. Association, Composition and Aggregation in UI5, CRM, S/4HANA and C4C

    UI5 UI5使用Association和Aggregation描述控件之间的关系. Aggregation:parent和子控件在lifecycle上存在依赖关系: When a ManagedOb ...

  7. vuejs使用组件的细节点

    is属性 <div id='root'> <table> <tbody> <row></row> <row></row&g ...

  8. 2017.11.2 JavaWeb----第六章 Servlet技术

    JavaWeb ------第六章 Servlet技术 (1)在Web应用程序开发中,一般由JSP JavaBean技术和 Servlet技术的结合实现MVC开发模式.在MVC开发模式中将Web程序的 ...

  9. C#继承的多态性

    C#继承的多态性 当一个类A派生出新类B时,这个基类A在新类B中可以表现为不同的类型:用作它自己的类型.基类型,或者在实现接口时用作接口类型,我们将这种情况称为多态性. C#中的每种类型都是多态性的, ...

  10. caffe的损失函数

    损失函数,一般由两项组成,一项是loss term,另外一项是regularization term. J=L+R 先说损失项loss,再说regularization项. 1. 分对得分1,分错得分 ...