基础语法:

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

  1. python3操作MySQL数据库

    安装PyMySQL 下载地址:https://pypi.python.org/pypi/PyMySQL 1.把操作Mysql数据库封装成类,数据库和表先建好 import pymysql.cursor ...

  2. Python3 操作mysql数据库

    python关于mysql的API--pymysql模块 pymsql是Python中操作MySQL的模块,其使用方法和py2的MySQLdb几乎相同. 模块安装 pip install pymysq ...

  3. python3操作mysql数据库增删改查

    #!/usr/bin/python3 import pymysql import types db=pymysql.connect("localhost","root&q ...

  4. python3操作mysql数据库表01(基本操作)

    #!/usr/bin/env python# -*- coding:UTF-8 -*- import requestsfrom bs4 import BeautifulSoupfrom bs4 imp ...

  5. python3操作MySQL数据库,一次插入多条记录的方法

    这里提供一个思路,使用字符串拼接的方法,将sql语句拼接出来,然后去执行: l = ["] s = '-' print(s.join(l))

  6. python3操作mysql数据库表01(封装查询单条、多条数据)

    #!/usr/bin/env python# -*- coding:UTF-8 -*- import pymysql# import os'''封装查询单条.多条数据'''# os.environ[' ...

  7. python接口自动化(三十八)-python操作mysql数据库(详解)

    简介 现在的招聘要求对QA人员的要求越来越高,测试的一些基础知识就不必说了,来说测试知识以外的,会不会一门或者多门开发与语言,能不能读懂代码,会不会Linux,会不会搭建测试系统,会不会常用的数据库, ...

  8. 【tips】ORM - SQLAlchemy操作MySQL数据库

    优先(官方文档SQLAlchemy-version1.2): sqlalchemy | 作者:斯芬克斯 推荐一(长篇幅version1.2.0b3):python约会之ORM-sqlalchemy | ...

  9. python【第十二篇下】操作MySQL数据库以及ORM之 sqlalchemy

    内容一览: 1.Python操作MySQL数据库 2.ORM sqlalchemy学习 1.Python操作MySQL数据库 2. ORM sqlachemy 2.1 ORM简介 对象关系映射(英语: ...

随机推荐

  1. 机器学习实战一:kNN手写识别系统

    实战一:kNN手写识别系统 本文将一步步地构造使用K-近邻分类器的手写识别系统.由于能力有限,这里构造的系统只能识别0-9.需要识别的数字已经使用图形处理软件,处理成具有相同的色彩和大小:32像素*3 ...

  2. nvm版本管理工具安装

    windows 安装nvm步骤(shi'yongnvm-windows管理node版本): 瞎几把前言:mac上可以用n来管理node版本,私以为n很好用.家里的win7台式机一直没有安装过任何管理工 ...

  3. lintcode-136-分割回文串

    136-分割回文串 给定一个字符串s,将s分割成一些子串,使每个子串都是回文串. 返回s所有可能的回文串分割方案. 样例 给出 s = "aab",返回 [ ["aa&q ...

  4. linux tcpdump抓包,wireshark实时解析

    转自: http://www.freebuf.com/articles/wireless/6517.html   由于CentOS7上yum安装的wireshark对CoAP的解析支持不太完善,而我w ...

  5. hdu2421(数学,因式分解素数筛)

    Xiaoming has just come up with a new way for encryption, by calculating the key from a publicly view ...

  6. 颜色采集器colpick Color Picker

    简单 RGB.HSB.十六进制颜色选取器 jQuery 插件. 非常直观类似 Photoshop 的界面. 光明和黑暗很容易自定义 CSS3 外观. 28 KB 总由浏览器加载看起来不错甚至在 IE7 ...

  7. SRM708 div1 PalindromicSubseq(动态规划+容斥原理)

    题目大意:给定一个字符串,记X[i]为包含s[i]这个字符的所有子列是回文串的个数(注意是子列而不是子串),求出所有的X[i]*(i+1),然后异或起来作为返回结果 题解: 首先用容斥来想,如果当前枚 ...

  8. Powershell快速入门

    Powershell快速入门 来源: https://blog.csdn.net/u011054333/article/details/72567590 https://blog.csdn.net/u ...

  9. 【题解】SCOI2010幸运数字

    最近在学习容斥相关,于是就看到了这个题.一开始以为是补集转化,但是观察一下马上发现不可行,好像直接做会比较容易一些.一个数满足要求的充要条件即为是一个幸运数字的倍数,那么容斥可以轻松搞定,只要枚举是一 ...

  10. loj2540 「PKUWC 2018」随机算法

    pkusc 快到了--做点题涨涨 rp. 记 \(f(S,i)\) 表示 \(S\) 这个集合是决计不能选的(要么属于独立集,要么和独立集相连),或称已经考虑了的,\(i\) 表示此集合对应的最大独立 ...