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修改Excel数据的实例代码
Nov 01 Python
Python 抓取动态网页内容方案详解
Dec 25 Python
说一说Python logging
Apr 15 Python
Matplotlib 生成不同大小的subplots实例
May 25 Python
python 实现提取某个索引中某个时间段的数据方法
Feb 01 Python
Python通过TensorFlow卷积神经网络实现猫狗识别
Mar 14 Python
Python 占位符的使用方法详解
Jul 10 Python
Python udp网络程序实现发送、接收数据功能示例
Dec 09 Python
Python 面向对象静态方法、类方法、属性方法知识点小结
Mar 09 Python
Python用5行代码实现批量抠图的示例代码
Apr 14 Python
Python实现读取并写入Excel文件过程解析
May 27 Python
Python可视化神器pyecharts之绘制地理图表练习
Jul 07 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读取TXT文件向数据库导入海量数据的方法
2013/04/23 PHP
示例详解Laravel重置密码代码重构
2016/08/10 PHP
PHP实现登陆并抓取微信列表中最新一组微信消息的方法
2017/07/10 PHP
PHP cURL获取微信公众号access_token的实例
2018/04/28 PHP
Laravel框架中缓存的使用方法分析
2019/09/06 PHP
javascript实现的网页局布刷新效果
2008/12/01 Javascript
Node调试工具JSHint的安装及配置教程
2014/05/27 Javascript
jquery处理json对象
2014/11/03 Javascript
javascript实现的猜数小游戏完整实例代码
2016/05/10 Javascript
jQuery使用getJSON方法获取json数据完整示例
2016/09/13 Javascript
jQuery特殊符号转义的实现
2016/11/30 Javascript
BootStrap table删除指定行的注意事项(笔记整理)
2017/02/05 Javascript
js实现点击切换checkbox背景图片的简单实例
2017/05/08 Javascript
利用vscode编写vue的简单配置详解
2017/06/17 Javascript
vue2.0页面前进刷新回退不刷新的实现方法
2018/07/31 Javascript
js根据需要计算数组中重复出现某个元素的个数
2019/01/18 Javascript
vue实现表单录入小案例
2019/09/27 Javascript
原生js实现购物车
2020/09/23 Javascript
Python中还原JavaScript的escape函数编码后字符串的方法
2014/08/22 Python
Python基础知识_浅谈用户交互
2017/05/31 Python
python之文件读取一行一行的方法
2018/07/12 Python
python使用MQTT给硬件传输图片的实现方法
2019/05/05 Python
Python实现鼠标自动在屏幕上随机移动功能
2020/03/14 Python
New Balance英国官方网站:始于1906年,百年慢跑品牌
2016/12/07 全球购物
美国最好的保健品打折网店:Swanson
2017/08/04 全球购物
必须要使用游标的SQL语句有那些
2012/05/07 面试题
正隆泰信息技术有限公司上机题
2012/06/14 面试题
本科毕业生自我鉴定
2013/11/02 职场文书
班级寄语大全
2014/04/10 职场文书
优秀班主任事迹材料
2014/12/16 职场文书
检讨书大全
2015/01/27 职场文书
认真学习保证书
2015/02/26 职场文书
2015年秋学期师德师风建设工作总结
2015/10/23 职场文书
你会写报告?产品体验报告到底该怎么写?
2019/08/14 职场文书
七个Python必备的GUI库
2021/04/27 Python
python中对列表的删除和添加方法详解
2022/02/24 Python