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. Oracle数据库基本语句练习

    以ORACLE数据库为主提纲:第一部分.SQL语言基础 第一章:Oracle命令类别及sql简单语法介绍第二章:oracle的基本函数第三章:oracle的数据类型第四章:多表连接技术 第二部分.or ...

  2. IPV4基本知识介绍

    转自华为官网 1.1  介绍 定义 IPv4(Internet Protocol Version 4)协议族是TCP/IP协议族中最为核心的协议族.它工作在TCP/IP协议栈的网络层,该层与OSI参考 ...

  3. May 03rd 2017 Week 18th Wednesday

    Truth needs no colour; beauty, no pencil. 真理不需要色彩,美丽不需要涂饰. There is no absoulte truth and everlastin ...

  4. vs2008使用mysql链接错误

    原因是因为安装了64位的mysql,而开发工具室32位的,需要安装32位的开发库就可以了

  5. Uva 11806 拉拉队

    题目链接:https://uva.onlinejudge.org/external/118/11806.pdf 题意: n行m列的矩阵上放k个棋子,其中要求第一行,最后一行,第一列,最后一列必须要有. ...

  6. react里面 react-router4 跳转

    在react里面跳转的时候,一般可以用 <Link to='/tradeList' /> 但是我们在运用组件组合的时候经常会通过传参去判断,如果props传过来是参数,如果有link进行跳 ...

  7. stixel-world代码解读

    下边缘的求法应该是使用的第二篇论文的方法 上边缘的求法应该是使用的第一篇论文的方法 这是求上边缘的代码: std::vector<float> integralMembership(vma ...

  8. javaweb基础(39)_数据库连接池

    一.应用程序直接获取数据库连接的缺点 用户每次请求都需要向数据库获得链接,而数据库创建连接通常需要消耗相对较大的资源,创建时间也较长.假设网站一天10万访问量,数据库服务器就需要创建10万次连接,极大 ...

  9. C# return语句

    一.C# return语句 return语句用于终止它出现在其中的方法的执行,并将控制返回给调用方法. 语法格式如下: return ...;return语句还可以返回一个可选值.如果方法为void类 ...

  10. Python测量时间,用time.time还是time.clock

    在计算机领域有多种时间.第一种称作CPU时间或执行时间,用于测量在执行一个程序时CPU所花费的时间.第二种称作挂钟时间,测量执行一个程序时的总时间.挂钟时间也被称作流逝时间或运行时间.与CPU时间相比 ...