python 3.6 +pyMysql 操作mysql数据库(实例讲解)
作者:陈月白 发布时间:2024-01-19 16:38:39
标签:python,3.6,pyMysql,mysql,数据库
版本信息:python:3.6mysql:5.7pyMysql: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
来源:http://www.cnblogs.com/chenyuebai/p/7821996.html


猜你喜欢
- #{} 和 ${} 的区别#{} 匹配的是一个占位符,相当于 JDBC 中的一个?,会对一些敏感字符进行过滤,编译过后会对传递的值加上双引号
- 所谓取模运算,就是计算两个数相除之后的余数,符号是%。如a % b就是计算a除以b的余数。用数学语言来描述,就是如果存在整数n和m,其中0
- 在使用tp5时候把它部署到服务器上发现一个奇葩的事情,就是它默认访问config配置的默认页,无论怎么跳转到其他接口都不好使,最终重写了&n
- 每个 batch 前清空梯度,否则会将不同 batch 的梯度累加在一块,导致模型参数错误。然后我们将输入和目标张量都移动到所需的设备上,并
- 有一个需求是要在一个云监控的状态值中存储多个状态(包括可同时存在的各种异常、警告状态)使用了位运算机制在一个int型中存储。现在监控日志数据
- 读文件打开文件(文件需要存在)#打开文件f = open("data.txt","r")  
- 偶然发现了for…else…这种用法,使用这个实现了break跳出嵌套的for循环In [31]: for i in range(1,5):
- 本文实例讲述了python实现从一组颜色中找出与给定颜色最接近颜色的方法。分享给大家供大家参考。具体分析如下:这段代码非常有用,可以找到指定
- 前言python 可以做网站应用,也可以做客户端应用。但是客户端应用需要运行 py 脚本,如果用户不懂 python 就是一件比较麻烦的事情
- python 字典(dict)的特点就是无序的,按照键(key)来提取相应值(value),如果我们需要字典按值排序的话,那可以用下面的方法
- 前言例如,当使用pandas读取csv文件时,如果元素为空,则将其视为缺失值NaN(非数字)。使用dropna()方法删除缺失值,使用fil
- 终于完成了偶的拖动窗口,花了近15个小时,庆祝一下(*^__^*);以前写了IE下的功能,于是又写了firefox下的功能,在firefox
- 这篇文章主要介绍了Python线程条件变量Condition原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习
- <script language="javascript" type="text/javas
- Keras应该是最简单的一种深度学习框架了,入门非常的简单.简单记录一下keras实现多种分类网络:如AlexNet、Vgg、ResNet采
- 本文为大家分享了opencv基于Haar人脸检测和眼睛检测的具体代码,供大家参考,具体内容如下在这里,我们将进行人脸检测。最初,该算法需要大
- hypot()方法返回的欧几里德范数 sqrt(x*x + y*y).语法以下是hypot()方法的语法:hypot(x, y)
- 找了半天,以为numpy的where函数像matlab 的find函数一样好用,能够返回一个区间内的元素索引位置。结果没有。。(也可能是我没
- 开发环境:Pycharm 2018.3 + Anaconda3(5.3.0) + Python 3.7.1 + Numpy 1.15.4在此
- 目录一、定义二、作用三、导入1.import导入import 模块名from importfrom 模块名 import *总结一、定义包含