教你如何用Python连接MySQL,增删改查

271 阅读4分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第30天,点击查看活动详情

📢📢📢📣📣📣
哈喽!大家好,我是【IT邦德】,江湖人称jeames007,10年DBA工作经验
中国DBA联盟(ACDU)成员,目前从事DBA及程序编程😜😜😜
擅长Oracle、MySQL、PG 运维开发,备份恢复,安装迁移,性能优化、故障应急处理。
❤️❤️❤️感谢各位大可爱小可爱!❤️❤️❤️

摘要:教你如何用Python连接MySQL,增删改查

@文章目录

1. MySQL数据库的下载

官网:www.mysql.com/ 在这里插入图片描述 在这里插入图片描述

2. MySQL安装

2.1 安装.NET4

安装包: NDP452-KB2901907-x86-x64-AllOS-ENU.exe

在这里插入图片描述 在这里插入图片描述

3. PyMySQL模块安装

3.1 操作MySQL数据库
PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb
3.2 搭建PyMySQL环境
在使用 PyMySQL 之前,我们需要确保 PyMySQL 已安装,如果还未安装,我们可以使用以下命令安装最新版的PyMySQL。
pip install PyMySQL

在这里插入图片描述

如果使用命令无法安装,需要下载PyMySQL-1.0.2-py3-none-any.whl 文件(最新),进行安装。
(1) 进入python官网https://www.python.org 点击菜单PyPI ,如下图:

在这里插入图片描述 (2) 输入pymsql,进行搜索。如下图所示: 在这里插入图片描述 在这里插入图片描述 (3)点击下载 PyMySQL-1.0.2-py3-none-any.whl

在这里插入图片描述 (4)windows+R打开doc窗口,进入PyMySQL-0.9.3-py2.py3-none-any.whl文件所在目录,

##卸载
pip uninstall pymysql
##执行如命令进行安装
pip install PyMySQL-0.9.3-py2.py3-none-any.whl

4. 创建数据库表

在Python程序中,可以使用execute()在数据库中创建一个新表。
下面的实例代码演示了在PyMySQL数据库中创建新表student的过程。

4.1 创建数据库 在这里插入图片描述

Python 三引号
Python 中三引号可以将复杂的字符串进行赋值。
Python 三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符。
三引号的语法是一对连续的单引号或者双引号(通常都是成对的用)。
#导入pymysql
import pymysql
#创建连接
con=pymysql.connect(host='localhost',user='root',password='root',database='python_db',port=3306)
#创建游标对象
cur=con.cursor()
#编写创建表的sql
sql="""
    create table t_student(
     sno int primary key auto_increment,
     sname varchar(30) not null,
     age int(2),
     score float(3,1)
    )
"""
try:
    # 执行创建表的sql
    cur.execute(sql)
    print('创建表成功')
except Exception as e:
    print(e)
    print('创建表失败')
finally:
    #关闭连接
    con.close()

4.2 插入单条数据

#导入模块
import pymysql
#创建连接
con=pymysql.connect(host='localhost',password='root',user='root',port=3306,database='python_db')
#创建游标对象
cur=con.cursor()
#编写插入数据的sql
sql='insert into t_student(sname,age,score) values(%s,%s,%s)'
try:
    # 执行sql
    cur.execute(sql, ('小强', 18, 99.9))
    #提交事务
    con.commit()
    print('插入成功')
except Exception as e:
    print(e)
    con.rollback()
    print('插入失败')
finally:
    #关闭连接
    con.close()

4.3 插入多条数据

#导入模块
import pymysql
#创建连接
con=pymysql.connect(host='localhost',password='root',user='root',port=3306,database='python_db')
#创建游标对象
cur=con.cursor()
#编写插入数据的sql
sql='insert into t_student(sname,age,score) values(%s,%s,%s)'
try:
    # 执行sql
    cur.executemany(sql,[('小明',19,99.8),('小红',18,99.9),('晓丽',18,99.8),('小花',19,99.6)])
    #提交事务
    con.commit()
    print('插入成功')
except Exception as e:
    print(e)
    con.rollback()
    print('插入失败')
finally:
    #关闭连接
    con.close()

5. 数据库查询

Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
fetchone(): 该方法获取下一个查询结果集,结果集是一个对象。
fetchall(): 接收全部的返回结果行。
rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。

5.1 查询单条数据

#导入pymysql
import pymysql
#创建连接
con=pymysql.connect(host='localhost',database='python_db',user='root',password='root',port=3306)
#创建游标对象
cur=con.cursor()
#编写查询的sql
sql='select * from t_student where age=18'
#执行sql
try:
    cur.execute(sql)
    #处理结果集
    students=cur.fetchall()
    for student in students:
        sno=student[0]
        sname=student[1]
        age=student[2]
        score=student[3]
        print('sno:',sno,'sname:',sname,'age:',age,'score:',score)
except Exception as e:
    print(e)
    print('查询所有数据失败')
finally:
    #关闭连接
    con.close()

5.2 查询多条数据

#导入pymysql
import pymysql
#创建连接
con=pymysql.connect(host='localhost',database='python_db',user='root',password='root',port=3306)
#创建游标对象
cur=con.cursor()
#编写查询的sql
sql='select * from t_student where age=18'
#执行sql
try:
    cur.execute(sql)
    #处理结果集
    students=cur.fetchall()
    for student in students:
        sno=student[0]
        sname=student[1]
        age=student[2]
        score=student[3]
        print('sno:',sno,'sname:',sname,'age:',age,'score:',score)
except Exception as e:
    print(e)
    print('查询所有数据失败')
finally:
    #关闭连接
    con.close()

6. 数据库修改及删除

6.1 修改数据

#导入模块
import pymysql
#创建连接
con=pymysql.connect(host='127.0.0.1',database='python_db',user='root',password='root',port=3306)
#创建游标对象
cur=con.cursor()
#编写修改的sql
sql='update t_student set sname=%s where sno=%s'
#执行sql语句
try:
    cur.execute(sql,('张三丰',1))
    con.commit()
    print('修改成功')
except Exception as e:
    print(e)
    con.rollback()
    print('修改失败')
finally:
    #关闭连接
    con.close()

6.2 删除数据

#导入模块
import pymysql
#创建连接
con=pymysql.connect(host='127.0.0.1',database='python_db',user='root',password='root',port=3306)
#创建游标对象
cur=con.cursor()
#编写删除的sql
sql='delete from t_student where sname=%s'
#执行sql语句
try:
    cur.execute(sql,('张三丰'))
    con.commit()
    print('删除成功')
except Exception as e:
    print(e)
    con.rollback()
    print('删除失败')
finally:
    #关闭连接
    con.close()

b347adae8115422fa34e4bc45a9edc6b.gif