版本信息: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)

测试表:

执行结果:

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数据库的更多相关文章

  1. Python MySQLdb模块连接操作mysql数据库实例_python

    mysql是一个优秀的开源数据库,它现在的应用非常的广泛,因此很有必要简单的介绍一下用python操作mysql数据库的方法.python操作数据库需要安装一个第三方的模块,在http://mysql ...

  2. python使用pymysql操作mysql数据库

    1.安装pymysql pip install pymysql 2.数据库查询示例 import pymysql # 连接database conn =pymysql.connect(user=' , ...

  3. flask + pymysql操作Mysql数据库

    安装flask-sqlalchemy.pymysql模块 pip install flask-sqlalchemy pymysql ### Flask-SQLAlchemy的介绍 1. ORM:Obj ...

  4. python学习笔记之——操作mysql数据库

    Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数据库,你可以选择适合你项目的数据库: ...

  5. 使用pymysql操作mysql数据库

    PyMySQL的安装和连接 PyMySQL的安装 python3. -m pip install pymysql python连接数据库 import pymysql # 创建连接 conn = py ...

  6. 用pymysql操作MySQL数据库

    工具库安装 pip install pymysql 连接关闭数据库与增删改查操作 # 导入pymysql库 import pymysql # 打开数据库连接 # 参数1:数据库服务器所在的主机+端口号 ...

  7. PyMySQL操作mysql数据库(py3必学)

    一,安装PyMySQL Python是编程语言,MySQL是数据库,它们是两种不同的技术:要想使Python操作MySQL数据库需要使用驱动.这里选用PyMySQL驱动. 安装方式还是使用pip命令. ...

  8. pymysql操作mysql数据库

    1.建库 import pymysql # 建库 try: conn=pymysql.connect( host='127.0.0.1', port=3306, user='root', passwd ...

  9. 使用pymysql 操作MySQL数据库

    安装 pip install pymysql 注:连接前要有可使用的账户及有权限.可操作的数据库 先来一个栗子: import pymysql # 连接database conn = pymysql. ...

随机推荐

  1. Building roads

    Building roads Time Limit: 10000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Tot ...

  2. Rank of Tetris

    Rank of Tetris Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Tota ...

  3. Python面向对象篇之元类,附Django Model核心原理

    关于元类,我写过一篇,如果你只是了解元类,看下面这一篇就足够了. Python面向对象之类的方法和属性 本篇是深度解剖,如果你觉得元类用不到,呵呵,那是因为你不了解Django. 在Python中有一 ...

  4. aria-label

    元素中的 aria-label用来命名一个元素     它的值可以是任何字符   读屏软件就会读出aria-label里的内容 <div role=”form” aria-labelledby= ...

  5. 验证Oracle处理速度

    (这是2009年写的东西了,在网上看到有人对数据库批量操作的'速度'比较关注,于是就把这篇老文章整理了一下) 一.环境及前提 在244上(一台稍好一些的机器,做了RAID,机械硬盘,Raid几忘了), ...

  6. 删除“自豪的采用wordpress”

    网上的都是老一套了,方法不对. 听我的~ 先进入wordpress的安装目录,比如我的是:cd /www/wwwroot/www.yangnan.tk然后再进入,我的主题是twentyseventee ...

  7. 原生js绑定和解绑事件,兼容IE,FF,chrome

    主要是最近项目中用到了原生的js 解绑和绑定 事件  然后今天研究了一下,其实问题不大,不过要注意不要把单词写错了,今天我就找了好久单词写错了. 需求:当鼠标移上去以后,给Select加载元素,接着解 ...

  8. Python之argparse模块

    argparse 命令行参数解析模块,原optparse已经停止开发,建议替换为argparse 在python2.7后默认加入 parser ArgumentParser默认解析来源sys.argv ...

  9. vue2.0 带头冲锋(先穿鞋)

    事先说明:这次截图纯手工敲打,可不容易了.刚学会站直,不穿鞋,不得直接摔个狗食屎.(皮糙肉厚也顶不住啊). 废话不多了 !开始学基础.学过anguler1.0 ,会比较容易学vue. 溶解使用的是 v ...

  10. Redis Save 与 BGSAVE 的区别

    一,save保存数据到磁盘的方式: Redis Save 命令执行一个同步保存操作,将当前 Redis 实例的所有数据快照(snapshot)以 RDB 文件的形式保存到硬盘. 语法redis Sav ...