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()
相关推荐
爱喝水的鱼丶6 分钟前
SAP-MM:SAP采购组织全面学习指南:从概念到实战配置图解
运维·开发语言·数据库·学习·sap·mm模块·采购组织
深鱼~42 分钟前
DbGate数据库管理新方案:cpolar打造跨平台远程访问通道
数据库
WAWA战士1 小时前
mysql总结
数据库
熊思宇1 小时前
Sqlite“无法加载 DLL“e_sqlite3”: 找不到指定的模块”解决方法
数据库·sqlite
往事随风去1 小时前
面试官:mysql从数据库断开一段时间后,部分binlog已丢失,如何重建主从?
运维·数据库·mysql
J.Kuchiki1 小时前
【PostgreSQL内核学习 —— (SeqScan算子)】
数据库·postgresql
酷酷的崽7982 小时前
Redis 键(Key)的命令
数据库·redis·缓存
189228048612 小时前
NW622NW623美光固态闪存NW624NW635
大数据·网络·数据库·人工智能·microsoft·性能优化
云飞云共享云桌面2 小时前
1台电脑10个画图设计用怎么实现
linux·运维·服务器·网络·数据库·自动化·电脑
TTBIGDATA2 小时前
【Ambari监控】Ambari-Metrics 的分支研究
大数据·数据库·hadoop·ambari·bigtop·edp·hidataplus