(接口自动化)Python3操作MySQL数据库
基础语法:
import pymysql #导入模块
conn = pymysql.connect(host='localhost',user='root', passwd='123456', db='test', port=3306, charset='utf8',cursorclass = pymysql.cursors.DictCursor) #连接数据库,cursorclass = pymysql.cursors.DictCursor表示把查询的返回值变为字典格式
cur = conn.cursor() #建立指针
cur.execute("insert into users (username,password,email) values (%s,%s,%s)",("老齐","9988","qiwsir@gmail.com")) #插入单条数据
cur.executemany("INSERT DELAYED INTO users (username,pwd,mail) VALUES (%s,%s,%s)",('lili', 'ffff', 'gggg@qq.com'),('lili', 'sds', '321@qq.com')) #插入多条数据
conn.commit() #提交保存
以下是在接口测试中的实际应用
# -*- coding:utf-8 -*-
import pymysql,logging,os
class OperationDb_interface(object):
def __init__(self):
self.conn=pymysql.connect(host='localhost',
user='root', passwd='123456', db='test', port=3306, charset='utf8',cursorclass = pymysql.cursors.DictCursor) #创建数据库连接
self.cur=self.conn.cursor() #创建游标
#定义单条数据操作,增删改
def op_sql(self,param):
try:
self.cur.execute(param) #游标下执行sql语句
self.conn.commit() #提交数据
return True
except pymysql.Error as e:
print('Mysql Error %d:%s' % (e.args[0], e.args[1]))
logging.basicConfig(filename = os.path.join(os.getcwd(), './log.txt'),
level = logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
logger = logging.getLogger(__name__)
logger.exception(e)
return False #查询表中单条数据
def selectOne(self,condition):
try:
self.cur.execute(condition) #执行sql语句
results = self.cur.fetchone() #获取一条结果
except pymysql.Error as e:
results ='spl0001'
print('Mysql Error %d:%s' %(e.args[0], e.args[1]))
logging.basicConfig(filename = os.path.join(os.getcwd(), './log.txt'),
level = logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
logger = logging.getLogger(__name__)
logger.exception(e)
finally:
return results #查询表中多条数据
def selectAll(self,condition):
try:
self.cur.execute(condition)
self.cur.scroll(0, mode='absolute') #游标里的光标回到初始位置
results = self.cur.fetchall() #返回游标中所有结果
except pymysql.Error as e:
results='spl0001'
print('Mysql Error %d:%s' %(e.args[0], e.args[1]))
logging.basicConfig(filename = os.path.join(os.getcwd(), './log.txt'),
level = logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
logger = logging.getLogger(__name__)
logger.exception(e)
finally:
return results #定义表中插入多条数据操作
def insertMore(self, condition,argsall):
try:
self.cur.executemany(condition,argsall)
self.conn.commit()
return True
except pymysql as e:
results ='spl0001' #数据库执行错误
print('Mysql Error %d:%s' % (e.args[0], e.args[1]))
logging.basicConfig(filename = os.path.join(os.getcwd(), './log.txt'),
level = logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
logger = logging.getLogger(__name__)
logger.exception(e)
return False
#数据库关闭
def __del__(self):
if self.cur != None:
self.cur.close()
if self.conn != None:
self.conn.close() if __name__ == '__main__':
test=OperationDb_interface() #实例化类
sql1="insert into users (username,pwd,mail) VALUES (%s,%s,%s)"
argsall=[('lilyu','1234','1234@qq.com'),('lilu','124','124@qq.com'),('lil','14','14@qq.com')]
result=test.insertMore(sql1,argsall)
print(result)
(接口自动化)Python3操作MySQL数据库的更多相关文章
- python3操作MySQL数据库
安装PyMySQL 下载地址:https://pypi.python.org/pypi/PyMySQL 1.把操作Mysql数据库封装成类,数据库和表先建好 import pymysql.cursor ...
- Python3 操作mysql数据库
python关于mysql的API--pymysql模块 pymsql是Python中操作MySQL的模块,其使用方法和py2的MySQLdb几乎相同. 模块安装 pip install pymysq ...
- python3操作mysql数据库增删改查
#!/usr/bin/python3 import pymysql import types db=pymysql.connect("localhost","root&q ...
- python3操作mysql数据库表01(基本操作)
#!/usr/bin/env python# -*- coding:UTF-8 -*- import requestsfrom bs4 import BeautifulSoupfrom bs4 imp ...
- python3操作MySQL数据库,一次插入多条记录的方法
这里提供一个思路,使用字符串拼接的方法,将sql语句拼接出来,然后去执行: l = ["] s = '-' print(s.join(l))
- python3操作mysql数据库表01(封装查询单条、多条数据)
#!/usr/bin/env python# -*- coding:UTF-8 -*- import pymysql# import os'''封装查询单条.多条数据'''# os.environ[' ...
- python接口自动化(三十八)-python操作mysql数据库(详解)
简介 现在的招聘要求对QA人员的要求越来越高,测试的一些基础知识就不必说了,来说测试知识以外的,会不会一门或者多门开发与语言,能不能读懂代码,会不会Linux,会不会搭建测试系统,会不会常用的数据库, ...
- 【tips】ORM - SQLAlchemy操作MySQL数据库
优先(官方文档SQLAlchemy-version1.2): sqlalchemy | 作者:斯芬克斯 推荐一(长篇幅version1.2.0b3):python约会之ORM-sqlalchemy | ...
- python【第十二篇下】操作MySQL数据库以及ORM之 sqlalchemy
内容一览: 1.Python操作MySQL数据库 2.ORM sqlalchemy学习 1.Python操作MySQL数据库 2. ORM sqlachemy 2.1 ORM简介 对象关系映射(英语: ...
随机推荐
- 为什么logstash进程的CPU使用率100%?
机器上有个进程cpu使用率很高,近100%了, Tasks: 120 total, 2 running, 118 sleeping, 0 stopped, 0 zombie%Cpu(s): 99.0 ...
- 目标检测之Faster-RCNN的pytorch代码详解(模型准备篇)
十月一的假期转眼就结束了,这个假期带女朋友到处玩了玩,虽然经济仿佛要陷入危机,不过没关系,要是吃不上饭就看书,吃精神粮食也不错,哈哈!开个玩笑,是要收收心好好干活了,继续写Faster-RCNN的代码 ...
- React错误总结(三)
神坑react native之Cannot Add a child that doesn't have a YogaNode to a parent with out a measure functi ...
- AMF3 在Unity中使用AMF3和Java服务器通信
现在在做的项目是一个网页游戏的移植到移动端. 所以服务器直接使用原来的代码.原来的游戏是as3实现,使用flash amf3数据通信. Unity 使用C#作为脚本语言,所以就需要.net的amf3解 ...
- 修改maven远程仓库为阿里的maven仓库(复制)
maven之一:maven安装和eclipse集成 maven作为一个项目构建工具,在开发的过程中很受欢迎,可以帮助管理项目中的bao依赖问题,另外它的很多功能都极大的减少了开发的难度,下面来介绍ma ...
- HDU B-Ignatius and the Princess IV
http://acm.hdu.edu.cn/showproblem.php?pid=1029 Problem Description "OK, you are not too bad, em ...
- 【WebService】——契约优先
相关博客: [WebService]--入门实例 [WebService]--SOAP.WSDL和UDDI 前言: 我们先来看一个契约优先的开发实例,通过熟悉他的开发流程,最后再和代码优先的方式进行比 ...
- 【WebService】——SOAP、WSDL和UDDI
WebService的三要素:SOAP.WSDL和UDDI.soap用来描述传递信息的格式,wsdl描述如何访问具体的接口,uddi管理.分发查询WebService. 1.SOAP SOAP Sim ...
- [C/C++] C++声明和定义的区别
·变量定义:用于为变量分配存储空间,还可为变量指定初始值.程序中,变量有且仅有一个定义. ·变量声明:用于向程序表明变量的类型和名字. ·定义也是声明:当定义变量时我们声明了它的类型和名字. ·ext ...
- Small things are better
Yesterday I had fun time repairing 1.5Tb ext3 partition, containing many millions of files. Of cours ...