猿创征文|Python基础——Visual Studio版本——第六章 MySQL操作

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: 猿创征文|Python基础——Visual Studio版本——第六章 MySQL操作

1、环境import pymysql  # 链接MySQL

db = pymysql.connect(host='rm-bp1zq3879r28p726lco.mysql.rds.aliyuncs.com',
                    port=3306, 
                    user='qwe8403000', 
                    password='Qwe8403000', 
                    db='mytest', 
                    charset='utf8')
print(db)

配置

pip3 config set global.index-url https://repo.huaweicloud.com/repository/pypi/simple

pip3 config list

pip3 install --upgrade pip

pip3 install pymysql

2、环境引入与连接测试

数据库是我阿里的数据库,可以用到23年。做测试没问题。


输入顺序:host连接地址,port连接端口号,user连接用户名,password连接密码,db连接数据库,charset连接的编码格式。



         

image.png

3、创建数据库表

核心编码


conn = pymysql.connect()  # 创建连接
cursor = conn.cursor()   #获取游标对象
rows = cursor.execute(sql) #执行SQL语句
conn.commit()  #提交数据库连接,如果是增、删、改操作,则必须提交
cursor.close() #关闭游标对象
conn.close()   #关闭数据库连接

image.png

import pymysql
#创建数据库连接
conn = pymysql.connect(host='rm-bp1zq3879r28p726lco.mysql.rds.aliyuncs.com',
                    port=3306, 
                    user='qwe8403000', 
                    password='Qwe8403000', 
                    db='mytest', 
                    charset='utf8')
cursor = conn.cursor()   #获取游标对象
#定义创建user表的sql语句,使用三引号'''表示格式化字符串
sql = """CREATE TABLE mytestuser20220829 ( userid int(8) NOT NULL auto_increment,
  username varchar(50) NOT NULL,
  password varchar(50) default NULL,
  PRIMARY KEY  (userid))"""
rows = cursor.execute(sql) #执行SQL语句
conn.commit()  #提交数据库连接,如果是增、删、改操作,则必须提交
print("mytestuser20220829表创建成功")
cursor.close() #关闭游标对象
conn.close()   #关闭数据库连接



4、增删改语句测试

游标可以多次执行sql语句,最终进行commit即可。


import pymysql
#创建数据库连接
conn = pymysql.connect(host='rm-bp1zq3879r28p726lco.mysql.rds.aliyuncs.com',
                    port=3306, 
                    user='qwe8403000', 
                    password='Qwe8403000', 
                    db='mytest', 
                    charset='utf8')
cursor = conn.cursor()   #获取游标对象
#定义创建user表的sql语句,使用三引号'''表示格式化字符串
sqlInsert1 = "insert into mytestuser20220829 values(0,'{0}',{1})".format("王语嫣", "123")
sqlInsert2 = "insert into mytestuser20220829 values(0,'{0}',{1})".format("小龙女","123")
sqlInsert3 = "insert into mytestuser20220829 values(0,'{0}',{1})".format("赵灵儿", "321")
sqlInsert4 = "insert into mytestuser20220829 values(0,'{0}',{1})".format("删除测试", "321")
cursor.execute(sqlInsert1)
cursor.execute(sqlInsert2)
cursor.execute(sqlInsert3)
cursor.execute(sqlInsert4)
sqlUpdate = "update mytestuser20220829 set password='{0}' where username='{1}'".format("潇洒的姑娘", "赵灵儿")
cursor.execute(sqlUpdate)
sqlDelete = "delete from mytestuser20220829 where username='{0}'".format("删除测试")
cursor.execute(sqlDelete)
#  提交
conn.commit()
#  关闭游标
cursor.close()
#  关闭数据库
conn.close()


image.png


5、查询语句测试

使用fetchall函数就可以获取游标中的数据了。


import pymysql
#创建数据库连接
conn = pymysql.connect(host='rm-bp1zq3879r28p726lco.mysql.rds.aliyuncs.com',
                    port=3306, 
                    user='qwe8403000', 
                    password='Qwe8403000', 
                    db='mytest', 
                    charset='utf8')
cursor = conn.cursor()   #获取游标对象
sql = "select * from mytestuser20220829"  # 执行SQL
cursor.execute(sql)  # 回去返回集合
data = cursor.fetchall()
for item in data:
    print(item[0])
    print(item[1])
    print(item[2])
#  关闭游标
cursor.close()
#  关闭数据库
conn.close()

image.png



6、事务测试

ACID_MySQL事务的四大特性详解(MySQL高频面试题)_红目香薰的博客-CSDN博客


异常提交

异常回滚测试,我这里一个正确的insert一个错误的,正确的肯定是能添加成功的,但是有由于第二个语句错误,所以回滚的时候一同回滚。


import pymysql
#创建数据库连接
conn = pymysql.connect(host='rm-bp1zq3879r28p726lco.mysql.rds.aliyuncs.com',
                    port=3306, 
                    user='qwe8403000', 
                    password='Qwe8403000', 
                    db='mytest', 
                    charset='utf8')
cursor = conn.cursor()   #获取游标对象
try:
    sql1 = "insert into mytestuser20220829 values(0,'{0}',{1})".format("事务测试1", "666")
    cursor.execute(sql1)  # 回去返回集合
    sql2 = "insert into mytestuser20220829 values(0,'{0}',{1},{2})".format("事务测试2", "666",66)
    cursor.execute(sql2)  # 回去返回集合
    conn.commit()
except:
    print("有异常,数据库回滚")
    conn.rollback()  #回滚事务,之前的修改操作都不生效
#  关闭游标
cursor.close()
#  关闭数据库
conn.close()

异常回滚,可以看到没有任何数据添加成功。

image.png



无异常提交

两个sql语句都是正确的sql,一同提交并无异常。


import pymysql
#创建数据库连接
conn = pymysql.connect(host='rm-bp1zq3879r28p726lco.mysql.rds.aliyuncs.com',
                    port=3306, 
                    user='qwe8403000', 
                    password='Qwe8403000', 
                    db='mytest', 
                    charset='utf8')
cursor = conn.cursor()   #获取游标对象
try:
    sql1 = "insert into mytestuser20220829 values(0,'{0}',{1})".format("事务测试1", "666")
    cursor.execute(sql1)  # 回去返回集合
    sql2 = "insert into mytestuser20220829 values(0,'{0}',{1})".format("事务测试2", "666")
    cursor.execute(sql2)  # 回去返回集合
    conn.commit()
except:
    print("有异常,数据库回滚")
    conn.rollback()  #回滚事务,之前的修改操作都不生效
#  关闭游标
cursor.close()
#  关闭数据库
conn.close()


两条sql都添加成功。


image.png


7、封装DBHelper.py

主要进行增删改、查询两个函数的封装,其中init是初始化参数,getConnect是获取游标


import pymysql
class DBHelper():
    def __init__(self):
        # 数据库连接参数
        self.host = "rm-bp1zq3879r28p726lco.mysql.rds.aliyuncs.com"
        self.user = "qwe8403000"
        self.pwd = "Qwe8403000"
        self.db = "mytest"
        self.charset = "utf-8"
    # 获取游标
    def getConnect(self):
        if not self.db:
            raise(NameError, "没有设置数据库信息")
        self.conn = pymysql.connect(host=self.host, port=3306, user=self.user, passwd=self.pwd, db=self.db, charset="utf8mb4")
        # 按照字典的方式返回
        cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
        if not cursor:
            raise(NameError, "连接数据库失败")
        else:
            return cursor
    # 查
    def query(self, sql):
        cursor = self.getConnect()
        cursor.execute(sql)
        result = cursor.fetchall()  # 获取查询的所有数据
        # 查询完毕后必须关闭连接
        self.conn.close()
        return result
   # 增删改
    def excute(self, sql):
        cursor = self.getConnect()
        cursor.execute(sql)
        self.conn.commit()
        self.conn.close()


使用DBHelper测试


from DBHelper import DBHelper
db=DBHelper()
db.excute("insert into mytestuser20220829 values(0,'{0}',{1})".format("DBHelper测试数据1", "666"))
db.excute("insert into mytestuser20220829 values(0,'{0}',{1})".format("DBHelper测试数据2", "666"))
db.excute("insert into mytestuser20220829 values(0,'{0}',{1})".format("DBHelper测试数据3", "666"))
db.excute("insert into mytestuser20220829 values(0,'{0}',{1})".format("DBHelper测试数据4", "666"))
db.excute("insert into mytestuser20220829 values(0,'{0}',{1})".format("DBHelper测试数据5", "666"))
result=db.query("select * from mytestuser20220829")
print(result)

image.png


封装完毕。

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
19天前
|
关系型数据库 MySQL 数据库
mysql卸载、下载、安装(window版本)
mysql卸载、下载、安装(window版本)
|
25天前
|
存储 SQL 关系型数据库
【MySQL】4. 表的操作
【MySQL】4. 表的操作
21 0
|
1月前
|
SQL 关系型数据库 MySQL
|
1月前
|
关系型数据库 MySQL 数据库
django4版本提示 django.db.utils.NotSupportedError: MySQL 8 or later is required (found 5.7.26)
在学习Django时,用户遇到`django.db.utils.NotSupportedError`,提示需要MySQL 8.0.25或更高版本,但其系统上是5.7.26。为解决这个问题,用户决定不升级MySQL,而是选择注释掉Django源码中的数据库版本检查。通过Python命令行找到Django安装路径,进入`db/backends/base/base.py`,注释掉`self.check_database_version_supported()`函数
135 0
|
29天前
|
SQL 关系型数据库 MySQL
【MySQL技术专题】「问题实战系列」深入探索和分析MySQL数据库的数据备份和恢复实战开发指南(8.0版本升级篇)
【MySQL技术专题】「问题实战系列」深入探索和分析MySQL数据库的数据备份和恢复实战开发指南(8.0版本升级篇)
96 0
|
24天前
|
缓存 关系型数据库 MySQL
MySQL查询优化:提速查询效率的13大秘籍(合理使用索引合并、优化配置参数、使用分区优化性能、避免不必要的排序和group by操作)(下)
MySQL查询优化:提速查询效率的13大秘籍(合理使用索引合并、优化配置参数、使用分区优化性能、避免不必要的排序和group by操作)(下)
|
2天前
|
开发者 Python
six,一个神奇的 Python 版本兼容工具库!
six,一个神奇的 Python 版本兼容工具库!
11 4
|
2天前
|
Ubuntu Python
ubuntu升级Python版本
现在,你已成功升级了Python版本并可以使用新版本进行开发和运行程序。
13 1
|
11天前
|
Python
IDA3.12版本的python,依旧报错IDAPython: error executing init.py.No module named ‘impRefer to the message win
IDA3.12版本的python,依旧报错IDAPython: error executing init.py.No module named ‘impRefer to the message win
|
25天前
|
Python Windows
【Python】Windows如何在cmd中切换python版本
【Python】Windows如何在cmd中切换python版本