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中精确输出JSON浮点数的方法
Apr 18 Python
python在指定目录下查找gif文件的方法
May 04 Python
深入解析Python中的descriptor描述器的作用及用法
Jun 27 Python
使用Python设计一个代码统计工具
Apr 04 Python
pygame游戏之旅 按钮上添加文字的方法
Nov 21 Python
Python利用heapq实现一个优先级队列的方法
Feb 03 Python
python 计算平均平方误差(MSE)的实例
Jun 29 Python
Python定时发送天气预报邮件代码实例
Sep 09 Python
图解python全局变量与局部变量相关知识
Nov 02 Python
基于Python的一个自动录入表格的小程序
Aug 05 Python
Django自带用户认证系统使用方法解析
Nov 12 Python
python自动化办公操作PPT的实现
Feb 05 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下对字符串的递增运算代码
2010/08/21 PHP
php自动注册登录验证机制实现代码
2011/12/20 PHP
关于PHP实现异步操作的研究
2013/02/03 PHP
基于ThinkPHP5.0实现图片上传插件
2017/09/25 PHP
记录几个javascript有关的小细节
2007/04/02 Javascript
再论Javascript下字符串连接的性能
2011/03/05 Javascript
基于jQuery捕获超链接事件进行局部刷新代码
2012/05/10 Javascript
JavaScript实现自动弹出窗口并自动关闭窗口的方法
2015/08/06 Javascript
Vue.JS入门教程之事件监听
2016/12/01 Javascript
Angular实现下拉框模糊查询功能示例
2018/01/03 Javascript
Vue2.0 v-for filter列表过滤功能的实现
2018/09/07 Javascript
JS实现扫码枪扫描二维码功能
2020/01/03 Javascript
js实现中文实时时钟
2020/01/15 Javascript
[02:11]2014DOTA2 TI专访VG战队Fenrir:队伍气氛良好
2014/07/11 DOTA
python读取csv文件示例(python操作csv)
2014/03/11 Python
Python实现简单的四则运算计算器
2016/11/02 Python
python bottle框架支持jquery ajax的RESTful风格的PUT和DELETE方法
2017/05/24 Python
Python3安装Scrapy的方法步骤
2017/11/23 Python
python检索特定内容的文本文件实例
2018/06/05 Python
python对列进行平移变换的方法(shift)
2019/01/10 Python
Python数据可视化教程之Matplotlib实现各种图表实例
2019/01/13 Python
离线状态下在jupyter notebook中使用plotly实例
2020/04/24 Python
python filecmp.dircmp实现递归比对两个目录的方法
2020/05/22 Python
python 字符串格式化的示例
2020/09/21 Python
Python 获取异常(Exception)信息的几种方法
2020/12/29 Python
Amaze UI 文件选择域的示例代码
2020/08/26 HTML / CSS
施华洛世奇澳大利亚官网:SWAROVSKI澳大利亚
2017/01/06 全球购物
比利时买床:Beter Bed
2017/12/06 全球购物
美味咖啡的顶级烘焙师:Cafe Britt
2018/03/15 全球购物
英国信箱在线鲜花速递公司:Bloom & Wild
2019/03/10 全球购物
Java如何调用外部Exe程序
2015/07/04 面试题
优秀技术工人先进材料
2014/02/17 职场文书
劳动工资科岗位职责范本
2014/03/02 职场文书
卖车协议书范例
2014/09/16 职场文书
催款律师函范文
2015/05/27 职场文书
公司财务管理制度
2015/08/04 职场文书