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网络编程之UDP通信实例(含服务器端、客户端、UDP广播例子)
Apr 25 Python
Python使用百度API上传文件到百度网盘代码分享
Nov 08 Python
介绍Python的Urllib库的一些高级用法
Apr 30 Python
Python lxml模块安装教程
Jun 02 Python
详解Python3中yield生成器的用法
Aug 20 Python
基于python list对象中嵌套元组使用sort时的排序方法
Apr 18 Python
解决Python下json.loads()中文字符出错的问题
Dec 19 Python
python3安装speech语音模块的方法
Dec 24 Python
Python 日期区间处理 (本周本月上周上月...)
Aug 08 Python
Python使用__new__()方法为对象分配内存及返回对象的引用示例
Sep 20 Python
Python3 ffmpeg视频转换工具使用方法解析
Aug 10 Python
python 使用tkinter与messagebox写界面和弹窗
Mar 20 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 无限级分类 获取顶级分类ID
2016/03/13 PHP
PHP实现图片压缩
2020/09/09 PHP
Laravel如何实现适合Api的异常处理响应格式
2020/06/14 PHP
JavaScript中常用的运算符小结
2012/01/18 Javascript
js跨浏览器实现将字符串转化为xml对象的方法
2013/09/25 Javascript
Js操作Select大全(取值、设置选中等等)
2013/10/29 Javascript
jQuery实现DIV层淡入淡出拖动特效的方法
2015/02/13 Javascript
jQuery插件开发精品教程让你的jQuery提升一个台阶
2016/01/27 Javascript
JS构造函数与原型prototype的区别介绍
2016/07/04 Javascript
用AngularJS的指令实现tabs切换效果
2016/08/31 Javascript
微信小程序  生命周期详解
2016/10/27 Javascript
seajs中最常用的7个功能、配置示例
2017/10/10 Javascript
浅谈react性能优化的方法
2018/09/05 Javascript
深入理解Vue 的钩子函数
2018/09/05 Javascript
使用 electron 实现类似新版 QQ 的登录界面效果(阴影、背景动画、窗体3D翻转)
2018/10/23 Javascript
JS面向对象之单选框实现
2020/01/17 Javascript
windows下create-react-app 升级至3.3.1版本踩坑记
2020/02/17 Javascript
vue微信分享插件使用方法详解
2020/02/18 Javascript
vue 解决IOS10低版本白屏的问题
2020/11/17 Javascript
在Vue中使用CSS3实现内容无缝滚动的示例代码
2020/11/27 Vue.js
Python多进程同步简单实现代码
2016/04/27 Python
Python使用Paramiko模块编写脚本进行远程服务器操作
2016/05/05 Python
python安装教程 Pycharm安装详细教程
2017/05/02 Python
Python算法之求n个节点不同二叉树个数
2017/10/27 Python
python中将一个全部为int的list 转化为str的list方法
2018/04/09 Python
Python多继承原理与用法示例
2018/08/23 Python
python3获取当前目录的实现方法
2019/07/29 Python
删除pycharm鼠标右键快捷键打开项目的操作
2021/01/16 Python
全面总结使用CSS实现水平垂直居中效果的方法
2016/03/10 HTML / CSS
用纯css3和html制作泡沫对话框实现代码
2013/03/21 HTML / CSS
如何查找和删除数据库中的重复数据
2014/11/05 面试题
俄语翻译实习生的自我评价分享
2013/11/06 职场文书
司机的工作范围及职责
2013/11/13 职场文书
公司财务自我评价分享
2013/12/17 职场文书
听证通知书
2015/04/24 职场文书
python实现简单倒计时功能
2021/04/21 Python