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. ...
随机推荐
- Codeforces Round #203 (Div. 2)B Resort
Resort Time Limit:2000MS Memory Limit:262144KB 64bit IO Format:%I64d & %I64u Submit Stat ...
- C#语言支持的特性,.NET却不支持,那么C#不被.NET支持的部分又是如何在.NET上运行的呢?
阅读<C#高级编程>系列丛书中,介绍C#与.NET的关系,提到C#是语言,.NET是平台(C#不是.NET的一部分),说".NET支持的一些特性,C#并不支持",这个可 ...
- c++学习笔记---03---从一个小程序说起2
从一个小程序说起2 要求:编写一个程序,要求用户输入一串整数和任意数目的空格,这些整数必须位于同一行中,但允许出现在该行中的任何位置.当用户按下键盘上的"Enter"键时,数据输入 ...
- android版火狐调试器
Remotely debugging Firefox for Android 使用火狐开发工具可以在桌面上进行远程代码的调试(FF26以上) 具体使用参考: https://developer.moz ...
- Icon font font face
font-face自定义字体,iconfont就是把各种图片做成字体.iconfont优势: 字体文件小,一般20-50kb: 容易编辑和维护,尺寸和颜色可以用css来控制: 透明完全兼容IE6: ...
- python基础知识——基于python3.6
语法糖 # # -*- coding: utf-8 -*- # #------------- # #--------- 语法糖--------------- # #------------------ ...
- 阿里云RDS for SQL Server使用的一些最佳实践
了解RDS的概念 这也是第一条,也是最重要的一条,在使用某项产品和服务之前,首先要了解该产品或服务的功能与限制,就像你买一个冰箱或洗衣机,通常也只有在阅读完说明书之后才能利用起来它们的所以功能,以及使 ...
- rem布局配合less的快速开发
最近在进行静态页面的制作,为了方便和快速的布局,自己整理了一套工具可以快速的进行工作,剩余的时间大家都懂的,话不多说,来看具体的东西吧! 1.ps 下载这个软件→cutterman 十分强大的切图功能 ...
- c++ const全局对象是如何处理的
我主要是记录一个发现,目前我不能解释,先作个记录. const 只是一个 语义约束,由编译器强制实施的.使被约束的对象不能被直接访问修改. 我用 『直接』这词,因为在代码段中 ,用一个const 指针 ...
- C#实现的apache htpasswd加密
一.VisualSvn Server 这个软件大家都知道,具体使用时创建用户名密码和组时,每次都要登陆到VisualSvn Server所在的机器上,次次如此... 由于一些原因要把这个用户管理的功能 ...