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()
相关推荐
马克Markorg3 小时前
常见的向量数据库和具有向量数据库能力的数据库
数据库
Coder_Boy_6 小时前
技术让开发更轻松的底层矛盾
java·大数据·数据库·人工智能·深度学习
helloworldandy6 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
数据知道7 小时前
PostgreSQL 故障排查:如何找出数据库中最耗时的 SQL 语句
数据库·sql·postgresql
qq_12498707537 小时前
基于SSM的动物保护系统的设计与实现(源码+论文+部署+安装)
java·数据库·spring boot·毕业设计·ssm·计算机毕业设计
枷锁—sha8 小时前
【SRC】SQL注入WAF 绕过应对策略(二)
网络·数据库·python·sql·安全·网络安全
Coder_Boy_8 小时前
基于SpringAI的在线考试系统-考试系统开发流程案例
java·数据库·人工智能·spring boot·后端
Gain_chance8 小时前
35-学习笔记尚硅谷数仓搭建-DWS层最近n日汇总表及历史至今汇总表建表语句
数据库·数据仓库·hive·笔记·学习
此生只爱蛋8 小时前
【Redis】主从复制
数据库·redis
马猴烧酒.8 小时前
【面试八股|JAVA多线程】JAVA多线程常考面试题详解
java·服务器·数据库