mysql数据库的封装
数据库封装类import pymysqlimport jsonclass My_databa(object): def __init__(self,pwd='****',name='表名',user='root',host='localhost',port=3306): self.conn=pymysql.connect(user=user,host=host,db=name,port=port,password=pwd,charset='utf8') self.cursor=self.conn.cursor() def __enter__(self):#with调用方法 return self def __del__(self):#析构方法 try: self.cursor.close() self.conn.close() except: pass#插入方法 def insert(self,table,*args): for x in args: keys='' values='' for key,value in x.items(): keys=keys+key+',' values = values + '"' + str(value) + '"' + ',' values = values.strip(',') keys = keys.strip(',') sql = 'insert into {table}({keys}) values({values})'.format(table=table,keys=keys, values=values) print(sql) self.cursor.execute(sql) self.conn.commit() #删除操作 def delete(self,table,where): try: sql = 'delete from {table} where {where}'.format(table=table, where=where) self.cursor.execute(sql) # 提交事务 self.conn.commit() return self.cursor.rowcount except Exception as e: print(e) self.conn.rollback()#更新 def updata(self,table,where,data): try: mystr = '' for i, v in data.items(): # print(i,v) mystr = mystr + '{i}="{v}"'.format(i=i, v=v) + ',' mystr = mystr.strip(',') # print(mystr.strip(',')) sql = 'update {table} set {data} where {where}'.format(table=table, data=mystr, where=where) print(sql) self.cursor.execute(sql) self.conn.commit() return True except Exception as e: print(e) self.conn.rollback() finally: self.conn.close() def __exit__(self,*args):#with结束调用方法 self.__del__()if __name__=='__main__': # with open('list.txt', 'r', encoding='utf-8')as f: # h=json.load(f) with My_databa(pwd='***',name='ipdaili')as db: # db.insert('listip','h') db.delete('listip','id=3') db.updata('listip','id=30000',data={'ip':'0000000'}) 数据库封装函数import pymysql
#查询多条数据def select_all(sql): try: #打开数据库链接 db =pymysql.connect('localhost','root','123456','ai5_1',charset='utf8') #2.创建游标 cursor =db.cursor(pymysql.cursors.DictCursor) #3使用游标操作sql cursor.execute(sql) #4使用游标取得结果 res =cursor.fetchall() return res except Exception as e: print(e) finally: # 5.关闭数据库链接 db.close()#查询一条数据def select_one(sql): try: #打开数据库链接 db =pymysql.connect('localhost','root','123456','ai5_1',charset='utf8') #2.创建游标 cursor =db.cursor(pymysql.cursors.DictCursor) #3使用游标操作sql cursor.execute(sql) #4使用游标取得结果 res =cursor.fetchone() #5.关闭数据库链接 db.close() return res except Exception as e: print(e) finally: db.close()#插入操作,参数2个---1:表名 2:字典{字段名1:值1,字段名2:值2,}def insert(table,data): try: # 打开数据库链接 db =pymysql.connect('localhost','root','123456','ai5_1',charset='utf8') #创建游标 cursor=db.cursor() #使用游标执行sql keys = ','.join(data.keys()) values = '' for v in data.values(): # values += str(v)+',' values = values + '"'+str(v)+'"' + ',' values=values.strip(',') sql='insert into {table}({keys}) values({values})'.format(table=table,keys=keys,values=values) cursor.execute(sql) #提交事务 db.commit() return True except Exception as e: print(e) db.rollback() finally: db.close() #删除操作 delete from 表名 where 条件def delete(table,where=0): try: # 打开数据库链接 db = pymysql.connect('localhost', 'root', '123456', 'ai5_1', charset='utf8') # 创建游标 cursor = db.cursor() # 使用游标执行sql sql='delete from {table} where {where}'.format(table=table,where=where) cursor.execute(sql) #提交事务 db.commit() return cursor.rowcount except Exception as e: print(e) db.rollback() finally: db.close() #修改操作:update 表名 set 字段名='值',字段名2='值' where 条件def update(table,data,where): try: #打开数据库 #db=pymysql.connect(HOST,USER,PASSWORD,DB,PORT,charset=CHARSET) db = pymysql.connect('localhost', 'root', '123456', 'ai5_1', charset='utf8') #创建游标 cursor= db.cursor() #使用游标执行操作 #data={'age': 120} set ='' for k,v in data.items(): set = set +'%s = "%s" ,'%(k,v) set =set.strip(',') sql='update {table} set {set} where {where}'.format(table=table,set=set,where=where) print(sql) cursor.execute(sql) #提交操作 db.commit() except Exception as e: db.rollback() finally: # 关闭数据库 db.close()
转载于:https://www.cnblogs.com/nanyu/p/9032243.html
mysql数据库的封装相关推荐
- Python 操作MySql数据库(封装、优雅)
Python 记录操作MySql数据库(封装)--优雅 学了pymysql第三方库(pip install pymysql)来操作MySql数据库后,浅记一下对MySql进行 <关于我的MySq ...
- 封装连接mysql数据库_封装连接mysql数据库
封装连接mysql数据库 云服务器(Elastic Compute Service,简称ECS)是阿里云提供的性能卓越.稳定可靠.弹性扩展的IaaS(Infrastructure as a Servi ...
- python封装类连接mysql数据_python操作mysql数据库基本类封装
# -*- coding: UTF-8 -*- import MySQLdb as mdb class MysqldbHelper(object): """操作mysql ...
- nodejs对连接mysql数据库进行封装,使用库实现对数据库的增删查改操作
一.先安装mysql中间件 npm i mysql --save 二.config.json配置库文件 {"host": "localhost","p ...
- java mysql数据库封装_java-jdbc封装连接数据库工具
/************************************************************ Copyright (C), 1988-1999, Huawei Tech. ...
- thinkphp mysql类_PHP封装类似thinkphp连贯操作数据库的Db类(简单版)
为了方便操作Mysql数据库, 封装类似thinkphp连贯操作数据库的Db类<?php header("Content-Type:text/html;charset=utf-8&qu ...
- mysql函数封装_PHP访问MYSQL数据库封装类(附函数说明)
/* MYSQL 数据库访问封装类 MYSQL 数据访问方式,php4支持以mysql_开头的过程访问方式,php5开始支持以mysqli_开头的过程和mysqli面向对象 访问方式,本封装类以mys ...
- html checkbox 多选 根据数据库来显示选取和未选取,前端框架(2)DIV多选复选框框的封装和MySql数据库存取...
前端框架(二)DIV多选复选框框的封装和MySql数据库存取 图可以包含的寓意和含义是文字不能比拟的,先有一个效果图你也就知道这篇文章的主要内容是关于什么问题的,省去了一大堆文字的累述,看下面这张图: ...
- 封装mysql数据库_快速掌握 Mysql数据库对文件操作的封装
快速掌握 Mysql数据库对文件操作的封装 在查看Mysql对文件的操作中,它在不同的操作系统上对文件的操作,除了使用标准C运行库函数,包括open.close.seek等,在Win32下的文件和目录 ...
最新文章
- java什么叫实例化_在JAVA中实例化的确切含义是什么
- DQL数据查询语言——连接查询
- 吵架记-2020年6月22日16:47:45
- 搜索重复代码_通过MappedByteBuffer搜索大文件
- linux安装redis集群+常见报错
- java中or和and的优先级_x86处理器汇编语言AND和OR运算符优先级
- 树的几种遍历方式(递归/非递归)
- 利用selenium模块配合chromedriver把html文件转换为图片
- Linux Autofs自动挂载服务详解
- 机器学习实战 | Python机器学习算法应用实践
- Python电影售票系统
- Kubernetes能成大事,华为云的眼光“真毒”
- python结巴分词去掉虚词_jieba中文处理 python
- Ubuntu 16.04 创建无线热点
- c语言围棋报告,C++围棋程序实现报告.doc
- 澳门科技大学计算机专业研究生,澳门科技大学 计算机专业
- C语言取得int的位数
- Photo Album: 2008年5月-三亚爱琴海岸康年度假村-day4
- 常用第三方SDK目录
- 没有打不了的补丁切不了的面
热门文章
- 微信分组群发45028,微信分组群发has no masssend quota hint
- 2020下半年软考中级(系统集成项目管理工程师)(个人备考用)
- 计算机共享的媒体设备,多台计算机、手机和平板电脑中共享对文件和媒体的访问时怎么做...
- <Linux>计算机体系结构和操作系统
- 上海公积金销户问题--程序员
- 百度地图获取数据库点的坐标,并定时刷新到页面上,功能一
- SSM框架中实现地图查询及ECharts直方图功能
- 服务器日志文件已被清除恢复,Linux服务器入侵后日志文件删除/恢复方法
- php的qq邮箱正则表达式语法_正则表达式综合应用:qq邮箱提取
- i2c-test工具说明文档