python(六)枚举函数、操作MySQL数据库、操作redis、加密模块、jsonpath模块、写日志模块

本文介绍了Python中的enumerate函数,讲解了如何操作MySQL数据库和redis,探讨了加密技术如MD5和base64,还涉及了jsonpath模块解析JSON数据以及使用loguru进行日志记录。
摘要由CSDN通过智能技术生成

enumerate()枚举函数

enumerate()枚举函数,同时列出下标和内容。

l = [[1, 2, 3, 4],[5, 6, 7, 8]]
for row, i in enumerate(l):
    for col, j in enumerate(i):
      print(row, col, j)

运行结果:

0 0 1
0 1 2
0 2 3
0 3 4
1 0 5
1 1 6
1 2 7
1 3 8

操作MySQL数据库

使用pip install pymysql,安装pymysql模块,使用此模块连接MySQL数据库并操作数据库。

import pymysql

# 创建数据库链接
conn = pymysql.connect(
    host="ip地址", # 链接数据库的ip
    user="db_username",   # 用户名
    password="db_password",   # 用户密码
    db="db_name",     # 数据库名称
    port=3306,    # 数据库端口号,默认是3306
    charset='utf8',   # 字符集编码
    autocommit=True    # 自动提交
    )
    
# 创建游标
# cursor = conn.cursor()  # 创建普通的游标,返回结果为元组类型
cursor = conn.cursor(pymysql.cursors.DictCursor)    # 指定返回格式为字典

# 数据库操作
cursor.execute("select * from students limit 5;") # 查询数据库中数据
# cursor.execute("insert into students (name,phone,age,sex) values ('lilili','15000000001',18,'女');")  # 往数据库中插入数据
# cursor.execute('update students set name = "小白" where id = 1;')   # 更新数据库中数据 
# cur.execute('delete from students where id=50 ;')  # 删除数据库中数据

print(cursor.description)  # 查看数据库中表的字段信息

# conn.commit() #提交(insert,delect,update都需要提交。如果在创建数据库连接时设置autocommit=True,则不需要使用该语句提交数据库增删改的操作)

# print(cursor.fetchall())  # 获取sql执行的结果,获取表中所有数据,返回数据是二维数组
# print(cursor.fetchone())  # 只获取一条数据,返回数据是一维数组
print(cursor.fetchmany(5))  # 输入几获取几条数据,返回数据是二维数据组

for line in cursor:  # 取表中每行数据
    print(line)

cursor.close()  # 关闭游标
conn.close()    # 关闭数据库链接

普通游标和指定返回字典的游标的结果:

# conn.cursor()普通游标返回数据
((1, '小黑', '11111111111', 18, '男'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值