python 3.6 +pyMysql 操作mysql数据库(实例讲解)


Posted in Python onDecember 20, 2017

版本信息:python:3.6

mysql:5.7

pyMysql:0.7.11

################################################################# 
#author: 陈月白 
#_blogs: http://www.cnblogs.com/chenyuebai/ 
################################################################# 
# -*- coding: utf-8 -*-
class MysqlTools():
 """
 连接mysql
 库、表操作
 """
 def __init__(self,host,dbname,user,passwd,charset="utf8"):
 self.host = host
 self.dbname = dbname
 self.user = user
 self.passwd = passwd
 self.charset = charset

 def connectMysqlDatabase(self):
 """连接db"""
 try:
  #连接db
  connect = pymysql.connect(host=self.host,user=self.user,passwd=self.passwd,db=self.dbname,charset=self.charset)
  cursor = connect.cursor()
  databaseConnectInfo = self.user + "@" + "self.host" + "/" + self.dbname
  print("INFO:connect database %s success."%databaseConnectInfo)
  return connect,cursor
 except:
  traceback.print_exc()
  print("ERROR:FUNCTION connectMysqlDatabase connect mysql database failed.")

 def executeSqlLine(self,sqlLine):
 """执行单条sql语句"""
 if sqlLine and isinstance(sqlLine,str):
  print("INFO:now start connect mysql dababase.")
  connect,cursor = self.connectMysqlDatabase()
  executeResult = ""
  try:
  #游标执行sql
  cursor.execute(sqlLine)
  executeResult = cursor.fetchall() #获取所有执行结果
  cursor.close()    #关闭游标
  connect.commit()   #确认提交
  print("INFO:execute sql sucess. sqlLine = ", sqlLine)
  except Exception as e:
  print("ERROR:execute sql failed.errorInfo =",e)
  print("ERROR:FUNCTION executeSql execute failed.sqlLine =",sqlLine)
  connect.rollback()   #回滚db
  return str(e) + " sqlLine = " + sqlLine
  #断开连接
  connect.close()
  print("INFO:connect closed.\n")
  return executeResult
 else:
  print("ERROR:param sqlLine is empty or type is not str.sqlLine = ",sqlLine)

 def executeBatchSql(self,sqlList):
 """
 批量执行sql
 exp: executeBatchSql([sql_1,
    sql_2,
    sql_3,
    ......
    ])
 """
 finalResultList = []
 if sqlList:
  for sql in sqlList:
  executeResult = self.executeSqlLine(sql)
  finalResultList.append(executeResult)
 else:
  print("ERROR:param sqlList is empty.")
 return finalResultList

测试代码:

# -*- coding: utf-8 -*-
from my_code.work_tools import WorkTools
mysql = WorkTools.MysqlTools("localhost","testdbname","rootuername","passwd")
#执行单行sql
ret1 = mysql.executeSqlLine("show databases")
#批量执行
ret2 = mysql.executeBatchSql([
       "show databases",
       "show tables",
       "update students_info set name = '王大花D' where id = 2",
       "select * from students_info",
       "error sql test"#异常sql测试
        ])
print("ret1 = ",ret1)
print("---------------------")
for i in ret2:
 print(i)

测试表:

python 3.6 +pyMysql 操作mysql数据库(实例讲解)

执行结果:

ret1 = (('information_schema',), ('mysql',), ('performance_schema',), ('sakila',), ('sys',), ('testdb',), ('world',))
---------------------
(('information_schema',), ('mysql',), ('performance_schema',), ('sakila',), ('sys',), ('testdb',), ('world',))
(('students_info',),)
()
((1, '陈月白', 'male', 25, '20176666', '1351234'), (2, '王大花D', 'female', 19, '19920816', '10086'), (3, '李强新', 'male', 18, '19941025', '10000'), (4, '王鹏', 'male', 20, '19970405', '10010'), (5, '钟齐', 'male', 22, '19970420', '123456789'), (6, '王大花', 'female', 15, '19981024', '12345678'))
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'error sql test' at line 1") sqlLine = error sql test

以上这篇python 3.6 +pyMysql 操作mysql数据库(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python 制作糗事百科爬虫实例
Sep 22 Python
分享给Python新手们的几道简单练习题
Sep 21 Python
python正则实现提取电话功能
Feb 24 Python
Python结合ImageMagick实现多张图片合并为一个pdf文件的方法
Apr 24 Python
PyCharm设置SSH远程调试的方法
Jul 17 Python
Python matplotlib画图与中文设置操作实例分析
Apr 23 Python
详解Python3 对象组合zip()和回退方式*zip
May 15 Python
python opencv如何实现图片绘制
Jan 19 Python
Python爬虫爬取电影票房数据及图表展示操作示例
Mar 27 Python
Python如何在main中调用函数内的函数方式
Jun 01 Python
Python高并发和多线程有什么关系
Nov 14 Python
Python操作PostgreSql数据库的方法(基本的增删改查)
Dec 29 Python
python实现ID3决策树算法
Dec 20 #Python
理解python中生成器用法
Dec 20 #Python
Python利用turtle库绘制彩虹代码示例
Dec 20 #Python
浅谈Python中range和xrange的区别
Dec 20 #Python
python机器学习实战之树回归详解
Dec 20 #Python
使用python 和 lint 删除项目无用资源的方法
Dec 20 #Python
python机器学习实战之K均值聚类
Dec 20 #Python
You might like
php实现当前页面点击下载文件的简单方法
2016/09/22 PHP
Yii2框架类自动加载机制实例分析
2018/05/02 PHP
关于Yii2框架跑脚本时内存泄漏问题的分析与解决
2019/12/01 PHP
javascript 火狐(firefox)不显示本地图片问题解决
2008/07/05 Javascript
ASP.NET jQuery 实例10 动态修改hyperlink的URL值
2012/02/03 Javascript
Highcharts 非常实用的Javascript统计图demo示例
2013/07/03 Javascript
jquery ztree实现下拉树形框使用到了json数据
2014/05/14 Javascript
chrome下img加载对height()的影响示例探讨
2014/05/26 Javascript
node.js中的fs.truncate方法使用说明
2014/12/15 Javascript
jQuery中unbind()方法用法实例
2015/01/19 Javascript
js中跨域方法原理详解
2015/07/19 Javascript
如何使用Bootstrap的modal组件自定义alert,confirm和modal对话框
2016/03/01 Javascript
Bootstrap Fileinput文件上传组件用法详解
2016/05/10 Javascript
详谈js中window.location.search的用法和作用
2017/02/13 Javascript
Angular父子组件通过服务传参的示例方法
2018/10/31 Javascript
记录vue项目中遇到的一点小问题
2019/05/14 Javascript
uploadify插件实现多个图片上传并预览
2019/09/30 Javascript
[01:03:54]Liquid vs IG 2018国际邀请赛小组赛BO2 第一场 8.17
2018/08/18 DOTA
Python天气预报采集器实现代码(网页爬虫)
2012/10/07 Python
Python入门_浅谈逻辑判断与运算符
2017/05/16 Python
Python编程之变量赋值操作实例分析
2017/07/24 Python
Python global全局变量函数详解
2018/09/18 Python
解决Django Static内容不能加载显示的问题
2019/07/28 Python
python 操作mysql数据中fetchone()和fetchall()方式
2020/05/15 Python
利用python对excel中一列的时间数据更改格式操作
2020/07/14 Python
基于python实现操作redis及消息队列
2020/08/27 Python
20行代码教你用python给证件照换底色的方法示例
2021/02/05 Python
分享30个新鲜的CSS3打造的精美绚丽效果(附演示下载)
2012/12/28 HTML / CSS
EJB2和EJB3在架构上的不同点
2014/09/29 面试题
Set里的元素是不能重复的,那么用什么方法来区分重复与否呢? 是用==还是equals()? 它们有何区别?
2014/07/27 面试题
模范家庭事迹材料
2014/02/10 职场文书
畜牧兽医本科生的自我评价
2014/03/03 职场文书
公司合并协议书范本
2014/09/30 职场文书
2015年社区重阳节活动总结
2015/07/30 职场文书
社区志愿服务活动感想
2015/08/07 职场文书
Python实现批量将文件复制到新的目录中再修改名称
2022/04/12 Python