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表格整理成一份表格
Jan 03 Python
[原创]python爬虫(入门教程、视频教程)
Jan 08 Python
tornado 多进程模式解析
Jan 15 Python
python3.6使用pymysql连接Mysql数据库
May 25 Python
Python3爬虫学习之爬虫利器Beautiful Soup用法分析
Dec 12 Python
对IPython交互模式下的退出方法详解
Feb 16 Python
Python pandas.DataFrame调整列顺序及修改index名的方法
Jun 21 Python
Python单元测试工具doctest和unittest使用解析
Sep 02 Python
python list数据等间隔抽取并新建list存储的例子
Nov 27 Python
Pandas将列表(List)转换为数据框(Dataframe)
Apr 24 Python
Python:__eq__和__str__函数的使用示例
Sep 26 Python
Python中使用Opencv开发停车位计数器功能
Apr 04 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调用C#开发的dll类库方法
2014/07/28 PHP
PHP的Yii框架中Model模型的学习教程
2016/03/29 PHP
php通过文件头判断格式的方法
2016/05/28 PHP
解决laravel-admin 自己新建页面里 js 需要刷新一次的问题
2019/10/03 PHP
离开页面时检测表单元素是否被修改,提示保存的js代码
2010/08/25 Javascript
jquery如何实现在加载完iframe的内容后再进行操作
2013/09/10 Javascript
用JS在浏览器中创建下载文件
2014/03/05 Javascript
JavaScript中的公有、私有、特权和静态成员用法分析
2014/11/20 Javascript
基于MVC4+EasyUI的Web开发框架形成之旅之界面控件的使用
2015/12/16 Javascript
JS禁用页面上所有控件的实现方法(附demo源码下载)
2015/12/17 Javascript
Ajax分页插件Pagination从前台jQuery到后端java总结
2016/07/22 Javascript
基于jQuery实现火焰灯效果导航菜单
2017/01/04 Javascript
基于canvas的二维码邀请函生成插件
2017/02/14 Javascript
javaScript日期工具类DateUtils详解
2017/12/08 Javascript
原生JS检测CSS3动画是否结束的方法详解
2019/01/27 Javascript
element-ui表格合并span-method的实现方法
2019/05/21 Javascript
node.js开发辅助工具nodemon安装与配置详解
2020/02/06 Javascript
微信小程序间使用navigator跳转传值问题实例分析
2020/03/27 Javascript
python实现的udp协议Server和Client代码实例
2014/06/04 Python
Python通过解析网页实现看报程序的方法
2014/08/04 Python
简单介绍Ruby中的CGI编程
2015/04/10 Python
详细解析Python当中的数据类型和变量
2015/04/25 Python
linux下python抓屏实现方法
2015/05/22 Python
Python栈算法的实现与简单应用示例
2017/11/01 Python
Python实现感知机(PLA)算法
2017/12/20 Python
Python的argparse库使用详解
2018/10/09 Python
python多线程http压力测试脚本
2019/06/25 Python
如何利用Python模拟GitHub登录详解
2019/07/15 Python
python爬虫 urllib模块url编码处理详解
2019/08/20 Python
pandas实现将日期转换成timestamp
2019/12/07 Python
HTML5移动端开发遇见的东西
2019/10/11 HTML / CSS
泰国演唱会订票网站:StubHub泰国
2018/02/26 全球购物
应聘美工求职信
2013/11/07 职场文书
优秀安全员事迹材料
2014/05/11 职场文书
党员干部群众路线个人整改措施
2014/09/18 职场文书
后勤工作个人总结
2015/02/28 职场文书