Python+pymysql中select count(*)/select *使用方式

1、问题概述?

在Python脚本中,我们通过:

1、使用select * from 查询返回多条数据

2、使用select count(*)返回单个数据

但是这两种在使用上略有不同,需要注意

使用pymysql之前需要先安装

pip install pyMySQL

2、select * 语句的使用及取值

当返回值为多条的时候使用cursor.fetchall()

复制代码
def 连接数据库函数():
    conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', port=3306, db='test', charset='utf8')
    cursor = conn.cursor()
    sql = 'select * from `student`  where  sex=""  AND name="Android" '
    cursor.execute(sql)
    list = cursor.fetchall()
    conn.close()
    print(list)
    return list

取值方式

for循环便利后,取值通过数组方式进行取值,索引从0开始。

复制代码
if __name__ == '__main__':
    list=连接数据库函数()
    for data in list:
        print("输出指定的参数:",data[0])

3、select count(*)语句的使用及取值

如果查询的结果返回的是单条数据使用cursor.fetchone()

复制代码
def 查询表格中数据的条数():
    conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', port=3306, db='test', charset='utf8')
    cursor = conn.cursor()
    sql = 'select count(*) from `student'
    cursor.execute(sql)
    count = cursor.fetchone()
    conn.close()
    return count[0]

取值方式

由于返回的就是数据的条数,直接使用即可。

4、其他语句的使用方式

4.1、update和delete语句的使用方式

修改动作需要使用commit进行提交操作

发生异常通过**conn.rollback()**回滚

复制代码
def 测试demo(id,name):
    conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', port=3306, db='test', charset='utf8')
    cursor = conn.cursor()
    sql='update `student` set name="'+name+'" where id="'+id+'"'
    cursor.execute(sql)
    sql2 = 'delete from `class'
    cursor.execute(sql3)
    try:
        conn.commit()
        print('操作成功')
    except Exception as e:
        print("操作失败")
        conn.rollback()
    finally:
        cursor.close()
        conn.close()

4.2、insert的语句的使用方式

insert的使用与其他基本相同,不能忽略资源的释放动作。

复制代码
def insertdemp(id....):
    conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', port=3306, db='test', charset='utf8')
    cursor = conn.cursor()
    sql = 'insert into student (id,name,sex,age,addr,pwd) values ('"+id+"',.....)' 
    cursor.execute(sql)
    conn.commit()
    cursor.close()
    conn.close()
相关推荐
德育处主任Pro25 分钟前
「py数据分析」04如何将 Python 爬取的数据保存为 CSV 文件
数据库·python·数据分析
许白掰44 分钟前
Linux入门篇学习——Linux 编写第一个自己的命令
linux·运维·数据库·嵌入式硬件·学习
打不了嗝 ᥬ᭄1 小时前
文件系统----底层架构
linux·运维·数据库
亲爱的非洲野猪2 小时前
Oracle与MySQL详细对比
数据库·mysql·oracle
Matrix702 小时前
Navicat实现MySQL数据传输与同步完整指南
数据库·mysql
Z字小熊饼干爱吃保安3 小时前
面试技术问题总结一
数据库·面试·职场和发展
极限实验室3 小时前
一键启动:使用 start-local 脚本轻松管理 INFINI Console 与 Easysearch 本地环境
数据库·docker
没有口袋啦3 小时前
《数据库》第一次作业:MySQL数据库账户及授权
数据库·mysql
星辰离彬4 小时前
Java 与 MySQL 性能优化:MySQL连接池参数优化与性能提升
java·服务器·数据库·后端·mysql·性能优化
张璐月6 小时前
mysql join语句、全表扫描 执行优化与访问冷数据对内存命中率的影响
数据库·mysql