前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python之Pymysql模块实现MySQL增删改查

Python之Pymysql模块实现MySQL增删改查

作者头像
王大力测试进阶之路
发布2020-01-17 17:54:33
3K0
发布2020-01-17 17:54:33
举报
文章被收录于专栏:橙子探索测试橙子探索测试

Python3 MySQL 数据库连接 - PyMySQL 驱动

PyMySQL 连接数据库,实现增删改查

什么是 PyMySQL?

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。

PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。

安装PyMySQL

$ pip install PyMySQL

1、创建数据库连接

在操作mysql之前,首先要与mysql建立连接

conn=pymysql.connect(host="mysql域名/ip",user="用户名",password="密码",db="库名",port=端口号3306,charset=‘utf-8’)

2、创建游标对象

当游标建立之时,就自动开始了一个隐形的数据库事务

#使用 cursor() 方法创建一个游标对象 cursor

cursor = conn.cursor()

3、执行sql语句

sql=“select * from user”

cursor.execute(sql) 或 cursor.execute(“select * from user”)

4、提交

conn.commit()

5、回滚

conn.rollback()方法回滚当前游标的所有操作。每一个方法都开始了一个新的事务

5、关闭游标

cursor.close()

6、关闭数据库连接

conn.close()

创建数据库连接

代码语言:javascript
复制
 
import pymysql
#创建数据库连接
db=pymysql.connect(host="数据库域名/ip",user="账号",password="密码",db="库名",port=3306)
print(db)
#使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
print(cursor)
#使用 execute() 方法执行 SQL 查询
cursor.execute("select * from user where mobile")
# 使用 fetchone() 方法.
results1= cursor.fetchone()#获取单条(第1条)数据
results2=cursor.fetchmany(3)#获取3条(2、3、4)数据
results3=cursor.fetchall() #获取全部(5-全部)数据
print(results3)
#关闭游标,又从起始位置开始
cursor.close()
# 关闭数据库连接
db.close()
 
 
C:\Users\wangli\PycharmProjects\AutoMation\venv\Scripts\python.exe C:/Users/wangli/PycharmProjects/AutoMation/case/test.py
<pymysql.connections.Connection object at 0x00000161DDC90E80>
<pymysql.cursors.Cursor object at 0x00000161DF8E44E0>
 
数据省略
 
Process finished with exit code 0

创建数据库表

代码语言:javascript
复制
#!/usr/bin/python3
 
import pymysql
 
# 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
 
# 使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
 
# 使用预处理语句创建表
sql = """CREATE TABLE EMPLOYEE (
         FIRST_NAME  CHAR(20) NOT NULL,
         LAST_NAME  CHAR(20),
         AGE INT,  
         SEX CHAR(1),
         INCOME FLOAT )"""
 
cursor.execute(sql)
 
# 关闭数据库连接
db.close()

数据库插入操作

代码语言:javascript
复制
 
import pymysql
#创建数据库连接
db=pymysql.connect(host="",user="",password="",db="ck",port=3306)
print(db)
#使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
print(cursor)
sql="INSERT INTO j.store (id,company_id,title,address,district,lon,lat,remark,updated_at,created_at,deleted_at) VALUES ('195', '61', '虹桥路店', '虹桥路1027号', '', '0.000000', '0.000000', NULL, '2019-03-15 14:54:29', '2019-03-15 14:54:29', NULL)"
 
 
#写法2
#cursor.execute('insert into stu(id,name,age) values(%s,%s,%s)',('201611001','xiaoqian',20))
 
#插入多条数据,具体数据用列表来保存,列表元素是元组
#cur.executemany('insert into stu(id,name,age) values(%s,%s,%s)',[('201611001','xiaoqian',20),('201611002','smile',21),('201611003','wood',23)])
 
 
 
try:
    #执行插入sql
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
except:
    # 如果发生错误则回滚
    db.rollback()
# 关闭数据库连接
db.close()
 
 
 
C:\Users\wangli\PycharmProjects\AutoMation\venv\Scripts\python.exe C:/Users/wangli/PycharmProjects/AutoMation/case/test.py
<pymysql.connections.Connection object at 0x00000295DEA90EB8>
<pymysql.cursors.Cursor object at 0x00000295E06B44E0>
 
Process finished with exit code 0

数据库查询操作

Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。

fetchone(): 该方法获取下一个查询结果集。结果集是一个对象

fetchall(): 接收全部的返回结果行.

rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行

1、单条sql语句查询

sql = "SELECT * FROM EMPLOYEE WHERE INCOME > %s" % (1000)

2、多条sql语句查询

代码语言:javascript
复制
import pymysql
#创建数据库连接
db=pymysql.connect(host="",user="",password="",db="",port=3306)
print(db)
#使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
print(cursor)
sql="select * from c.user limit 10"
try:
    #执行sql语句
    cursor.execute(sql)
    #查询所有记录
    results=cursor.fetchall()
    print(results)#打印10条数据
    for row in results:
        print(row)#循环打印每条数据
        user_id=row[0]#第1列字段
        mobile=row[1]#第2列字段
        print(user_id,mobile)#循环打印第1、2列字段
except:
    print('查询失败')
#关闭数据库连接
db.close()
 
 
C:\Users\wangli\PycharmProjects\AutoMation\venv\Scripts\python.exe C:/Users/wangli/PycharmProjects/AutoMation/case/test.py
<pymysql.connections.Connection object at 0x0000018E8BEDB748>
<pymysql.cursors.Cursor object at 0x0000018E8DB34550>
((2, '13888888888', '新', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554291602, 0, 1, 0, datetime.datetime(2019, 4, 3, 19, 37, 21), datetime.datetime(2019, 4, 3, 19, 49, 19), None), (75, '13888888888', '小', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554291602, 0, 1, 0, datetime.datetime(2019, 4, 3, 19, 37, 21), datetime.datetime(2019, 4, 3, 19, 49, 19), None), (139, '13888888888', '林', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554088503, 0, 2, 0, datetime.datetime(2019, 4, 1, 11, 11, 37), datetime.datetime(2019, 4, 1, 11, 15, 3), None), (190, '13888888888', '大', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554086702, 0, 1, 0, datetime.datetime(2019, 4, 1, 10, 40, 28), datetime.datetime(2019, 4, 1, 10, 45, 2), None), (192, '13888888888', '磊', '33010019900530156x', 0, '', '', '', 1, 1, '', '', '', '', '', 30, 13888888888, 0, 2, 0, datetime.datetime(2019, 3, 29, 17, 26, 56), datetime.datetime(2019, 4, 3, 19, 49, 19), None), (199, '13888888888', '一', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554086702, 0, 2, 0, datetime.datetime(2019, 4, 1, 10, 40, 28), datetime.datetime(2019, 4, 1, 16, 8, 3), None), (202, '13888888888', '三', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554086702, 0, 1, 0, datetime.datetime(2019, 4, 1, 10, 40, 29), datetime.datetime(2019, 4, 1, 10, 45, 2), None), (203, '13888888888', '四', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554086702, 0, 1, 0, datetime.datetime(2019, 4, 1, 10, 40, 29), datetime.datetime(2019, 4, 1, 10, 45, 2), None), (230, '13888888888', '大', '320382199303242813', 0, '', '', '', 1, 1, '', '', '', '', '', 30, 1554291602, 0, 2, 0, datetime.datetime(2019, 4, 3, 19, 37, 20), datetime.datetime(2019, 4, 3, 20, 11, 18), None), (278, '13700000003', '三', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554171902, 0, 2, 0, datetime.datetime(2019, 4, 2, 10, 24, 35), datetime.datetime(2019, 4, 2, 10, 25, 8), None))
(2, '13888888888', '林', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554291602, 0, 1, 0, datetime.datetime(2019, 4, 3, 19, 37, 21), datetime.datetime(2019, 4, 3, 19, 49, 19), None)
2 13888888888
(75, '13888888888', '马', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554291602, 0, 1, 0, datetime.datetime(2019, 4, 3, 19, 37, 21), datetime.datetime(2019, 4, 3, 19, 49, 19), None)
75 18817893609
(139, '13888888888', '林', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554088503, 0, 2, 0, datetime.datetime(2019, 4, 1, 11, 11, 37), datetime.datetime(2019, 4, 1, 11, 15, 3), None)
139 13888888888
(190, '13888888888', '徐', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554086702, 0, 1, 0, datetime.datetime(2019, 4, 1, 10, 40, 28), datetime.datetime(2019, 4, 1, 10, 45, 2), None)
190 13888888888
(192, '13888888888', '王', '330', 0, '', '', '', 1, 1, '', '', '', '', '', 30, 1553851802, 0, 2, 0, datetime.datetime(2019, 3, 29, 17, 26, 56), datetime.datetime(2019, 4, 3, 19, 49, 19), None)
192 13888888888
(199, '13888888888', '李', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554086702, 0, 2, 0, datetime.datetime(2019, 4, 1, 10, 40, 28), datetime.datetime(2019, 4, 1, 16, 8, 3), None)
199 13888888888
(202, '13888888888', '三', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554086702, 0, 1, 0, datetime.datetime(2019, 4, 1, 10, 40, 29), datetime.datetime(2019, 4, 1, 10, 45, 2), None)
202 13888888888
(203, '13888888888', '四', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554086702, 0, 1, 0, datetime.datetime(2019, 4, 1, 10, 40, 29), datetime.datetime(2019, 4, 1, 10, 45, 2), None)
203 13888888888
(230, '13888888888', '小', '320', 0, '', '', '', 1, 1, '', '', '', '', '', 30, 1554291602, 0, 2, 0, datetime.datetime(2019, 4, 3, 19, 37, 20), datetime.datetime(2019, 4, 3, 20, 11, 18), None)
230 13888888888
(278, '13700000003', '王', '', 0, '', '', '', 0, 1, '', '', '', '', '', 30, 1554171902, 0, 2, 0, datetime.datetime(2019, 4, 2, 10, 24, 35), datetime.datetime(2019, 4, 2, 10, 25, 8), None)
278 13700000003
 
Process finished with exit code 0

数据库更新操作

sql语句

sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')

sql="update c.user set sex=2 where mobile=18221124104"

cur.execute('update stu set age = %s where id = %s',(25,'201611006'))

代码语言:javascript
复制
import pymysql
#创建数据库连接
conn=pymysql.connect(host="",user="qa",password="Qa",db="c",port=3306)
print(conn)
#使用 cursor() 方法创建一个游标对象 cursor
cursor = conn.cursor()
print(cursor)
sql="update c.user set sex=2 where mobile=18221124104"
try:
    cursor.execute(sql)
    conn.commit()
except:
    conn.rollback()
conn.close()
 
 
C:\Users\wangli\PycharmProjects\AutoMation\venv\Scripts\python.exe C:/Users/wangli/PycharmProjects/AutoMation/case/test.py
<pymysql.connections.Connection object at 0x000002C281555A20>
<pymysql.cursors.Cursor object at 0x000002C2831944A8>
 
Process finished with exit code 0
 

删除操作

代码语言:javascript
复制
#!/usr/bin/python3
 
import pymysql
 
# 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 
# 使用cursor()方法获取操作游标 
cursor = db.cursor()
 
# SQL 删除语句
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 提交修改
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
 
# 关闭连接
db.close()

操作sql封装

代码语言:javascript
复制
#!/usr/bin/env python
# _*_coding:utf-8_*_
from common.readFile import ReadFile
import pymysql
import sys



class ExecSql(object):
    """
    执行sql语句类
    """

    _instance=None
    def __new__(cls,*args,**kwargs):
        if cls._instance is None:
            cls._instance=super().__new__(cls)
        return cls._instance

    def __init__(self):
        """
        初始化mysql配置
        :param platform_name:
        """
        #self.sql_conf = self._get_sql_conf(platform_name)
        self.sql_conf=None

    def _get_sql_conf(self, project):
        """
        获取mysql配置
        :param platform_name:
        :return:
        """
        try:
            return ReadFile().read_yaml('yaml_path')[project]['mysql']
        except:
            print("找不到对应项目:{0}".format(project))

    def connect_db(self):
        """
        连接mysql
        :return:
        """
        host = self.sql_conf['host']
        user = self.sql_conf['user']
        pwd = self.sql_conf['pwd']
        test_db = self.sql_conf['test_db']
        try:
            self.conn = pymysql.connect(host=host, user=user, password=pwd, db=test_db, port=3306, charset="utf8")
        except Exception as e:
            print("连接mysql失败:{0}".format(e))

    def get_cursor(self):
        """
        获取游标
        :return:
        """
        self.cursor=self.conn.cursor()
        return self.cursor

    def exec_sql(self,project,sql_type,sql):
        """
        执行sql语句
        :param sql_type:
        :param sql:
        :return:
        """
        self.sql_conf = self._get_sql_conf(project)
        try:
            if sql_type == 'select_one':
                self.connect_db()
                cursor = self.get_cursor()
                cursor.execute(sql)
                result = cursor.fetchone()
            elif sql_type == 'select_list':
                self.connect_db()
                cursor = self.get_cursor()
                cursor.execute(sql)
                result = cursor.fetchall()
            elif sql_type == 'update' or sql_type == 'del' or sql_type == 'insert':
                self.connect_db()
                result = self.get_cursor().execute(sql)
            self.conn.commit()
            self.cursor.close()
            self.conn.close()
            return result
        except Exception as e:
            print("sql类型或sql错误:{0}".format(e))


if __name__ == '__main__':
    test = ExecSql()
    a=test.exec_sql('lxk',"select_list","这里写sql语句")

+V信18221124104 加微信交流群

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-01-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 橙子探索测试 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 创建数据库连接
  • 创建数据库表
  • 数据库插入操作
  • 数据库查询操作
  • 数据库更新操作
  • 删除操作
  • 操作sql封装
相关产品与服务
云数据库 SQL Server
腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档