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. hibernate 初印象

    将要学习的内容: 1.HelloWorld a) xml b) annotation2.Hibernate 原理模拟 - 什么是 O/R Mapping 以及为什么要有 O/RMapping3.常见 ...

  2. java之操作mysql常用方法

    一般引用mysql-connector-java这个包. package DBManager; import java.sql.Connection; import java.sql.DriverMa ...

  3. 更改Anaconda中Jupyter的默认文件保存目录

    转载:https://blog.csdn.net/u014552678/article/details/62046638 总结:修改Anaconda中的Jupyter Notebook默认工作路径的三 ...

  4. 数组:获取GET的键名

    1.今天仓鼠遇到这个情况:通过$_GET获取参数,但是参数变成了键名形式 2.那仓鼠想要拿到这个键名,那就要:使用array_keys()获取数组中的所有键名,然后进行转换 代码如下: 结果: 以上 ...

  5. 4 - 函数&装饰器 and 迭代器&生成器

    函数是什么 函数一词来源于数学,但编程中的「函数」概念,与数学中的函数是有很大不同的.程序里函数的定义是: 定义:将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可 ...

  6. 关于(void**)及其相关的理解

    #define LOADBASSFUNCTION (f) *((void **)&f)=(void*)GetProcAddress (hBass,# f) 这一句话使用*((void**)&a ...

  7. 分治——sqtx

    题目描述 Given a string s, partition s such that every substring of the partition is a palindrome. Retur ...

  8. Altium_Designer-PCB的覆铜步骤

    1.覆铜的意义     覆铜,就是将PCB上闲置的空间作为基准面,然后用固体铜填充,这些铜区又称为灌铜.敷铜的意义在于,减小地线阻抗,提高抗干扰能力:降低压降,提高电源效率:还有,与地线相连,减小环路 ...

  9. SAP S4CRM和C4C的技术比较

    如果您对SAP S/4HANA for Customer Management(以下简称S4CRM)和SAP Cloud for Customer(以下简称C4C)不甚熟悉,那我建议您可以先浏览我之前 ...

  10. Maven一些零散的知识点

    Maven常用命令: 1. 创建Maven的普通java项目: mvn archetype:create -DgroupId=com.yida.framework -DartifactId=hello ...