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()
相关推荐
SelectDB技术团队5 小时前
冷热分层从建到验:Storage Policy 创建、表级与分区级绑定、SHOW TABLETS 验证的完整命令
大数据·数据库·elasticsearch·搜索引擎·数据分析·apache doris·冷热分层
YangYang9YangYan7 小时前
2027供应链计划校招:数学与应用数学专业如何把预测模型讲成业务决策?
人工智能·sql·算法
lambo mercy7 小时前
Day3:结构化输出
java·数据库·oracle
派小心.7 小时前
小程序分享链路中来源参数的传递校验
大数据·前端·数据库·人工智能·小程序·数据分析
Είναι η κοπέλα7 小时前
向量数据库与嵌入模型:Chroma/FAISS/Milvus 选型
数据库·milvus·faiss
IvorySQL8 小时前
从轮询到等待——PostgreSQL WAIT FOR LSN 特性深度解析
数据库·postgresql
OceanBase数据库官方博客8 小时前
被 VLDB 2027接收OceanBase 最新论文让数据库基(技术解析与实践)
数据库·人工智能·oceanbase
171320330计算机毕设编程9 小时前
计算机毕业设计 基于YOLO改进算法的车辆特征识别系统设计与实现--lw
java·大数据·python·sql·算法
创邻科技9 小时前
国产图数据库刷新 LDBC 世界纪录:创邻科技 Galaxybase 在 SF100、SF300、SF1000 测试中全面领先”
数据库·科技
GreatSQL社区9 小时前
主从复制SQL线程中断——字符集砸出的坑
java·数据库·算法