python 3.6 +pyMysql 操作mysql数据库
版本信息: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数据库的更多相关文章
- Python MySQLdb模块连接操作mysql数据库实例_python
mysql是一个优秀的开源数据库,它现在的应用非常的广泛,因此很有必要简单的介绍一下用python操作mysql数据库的方法.python操作数据库需要安装一个第三方的模块,在http://mysql ...
- python使用pymysql操作mysql数据库
1.安装pymysql pip install pymysql 2.数据库查询示例 import pymysql # 连接database conn =pymysql.connect(user=' , ...
- flask + pymysql操作Mysql数据库
安装flask-sqlalchemy.pymysql模块 pip install flask-sqlalchemy pymysql ### Flask-SQLAlchemy的介绍 1. ORM:Obj ...
- python学习笔记之——操作mysql数据库
Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数据库,你可以选择适合你项目的数据库: ...
- 使用pymysql操作mysql数据库
PyMySQL的安装和连接 PyMySQL的安装 python3. -m pip install pymysql python连接数据库 import pymysql # 创建连接 conn = py ...
- 用pymysql操作MySQL数据库
工具库安装 pip install pymysql 连接关闭数据库与增删改查操作 # 导入pymysql库 import pymysql # 打开数据库连接 # 参数1:数据库服务器所在的主机+端口号 ...
- PyMySQL操作mysql数据库(py3必学)
一,安装PyMySQL Python是编程语言,MySQL是数据库,它们是两种不同的技术:要想使Python操作MySQL数据库需要使用驱动.这里选用PyMySQL驱动. 安装方式还是使用pip命令. ...
- pymysql操作mysql数据库
1.建库 import pymysql # 建库 try: conn=pymysql.connect( host='127.0.0.1', port=3306, user='root', passwd ...
- 使用pymysql 操作MySQL数据库
安装 pip install pymysql 注:连接前要有可使用的账户及有权限.可操作的数据库 先来一个栗子: import pymysql # 连接database conn = pymysql. ...
随机推荐
- maximum shortest distance
maximum shortest distance Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/O ...
- Einbahnstrasse
Einbahnstrasse Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Tota ...
- Layui框架+PHP打造个人简易版网盘系统
网盘系统 大家应该都会注册过致命的一些网盘~如百度云.百科介绍:网盘,又称网络U盘.网络硬盘,是由互联网公司推出的在线存储服务,服务器机房为用户划分一定的磁盘空间,为用户免费或收费提供文件的存储. ...
- Linux修改date
与cn校时 ntpdate cn.pool.ntp.org 设置时区 TZ='Asia/Shanghai'; export TZ 刷新生效 source ~/.bashrc vi /etc/profi ...
- fs-max、file-nr和nofile的关系
1. file-max /proc/sys/fs/file-max: 这个文件决定了系统级别所有进程可以打开的文件描述符的数量限制,如果内核中遇到VFS: file-max limit <num ...
- 【S2-052】漏洞复现(CVE-2017-9805)
一.漏洞描述 Struts2 的REST插件,如果带有XStream组件,那么在进行反序列化XML请求时,存在未对数据内容进行有效验证的安全隐患,可能发生远程命令执行. 二.受影响版本 Struts2 ...
- windows下安装和redis主从配置(通过哨兵控制主从切换)
首先自己先得了解什么是redis,这里就不详做介绍什么是redis了,这篇文章主要讲的是怎么样配置 redis怎样配置主从关系和哨兵控制主从服务器的配置以及应用,就当是给自己记笔记吧! 1.下载red ...
- Spring框架——后处理器
Bean的后处理 Spring容器实例化Bean实例之后进行的增强处理,关于这里的描述之前有点错误,现在来纠正一下:这个过程有点像AOP,不过我们知道AOP是对方法而言的,而Bean后处理器是针对Ja ...
- String的Intern方法
jdk6 和 jdk7 下 intern 的区别 相信很多 JAVA 程序员都做做类似 String s = new String("abc")这个语句创建了几个对象的题目. 这种 ...
- 在JQuery中如何获取当前时间?
////发表时间(now) function p(s) { return s < 10 ? '0' + s : s; } var myDate = new Date(); //获取当前年 var ...