python3-mysql、redis数据库连接

PyMySQL模块

redis:string list set sortset hash

准备数据库

  1. 安装 mariadb-server
  2. 启动服务
  3. 创建名为 tedu1 的数据库【utf8】

PyMySQL 模块应用

连接数据库

创建连接是访问数据库的第一步

游标
  • 游标(cursor)就是游动的标识
  • 通俗的说,一条sql取出对应n条结果资源的接口/句柄,就是游标,沿着游标可以一次取出一行
import pymysql
conn=pymysql.connect(#1.创建连接
    host="192.168.88.11", port=3306,user="root",
    password="123456",db="tedu",charset="utf8")

cur = conn.cursor() #2.创建游标:操作数据库
#3.操作数据库
#-----------3.1 建表--------------
# create_bm = """create table bm(
#     bm_id int, bm_name char(10)
# );"""
#cur.execute(create_bm)


#-----------3.2 插入数据--------------
insert_bm="insert into bm values (%s,%s);" #单条插入
cur.execute(insert_bm,(1,""))
cur.executemany(insert_bm,[(2,"OPS"),(3,"TEST"),(4,"HR"),(5,"SALE")])

     #SQL注入
     #select * from tb where user={} and passwd={}
     #select * frim tb where user=zs and passwd=fds or 1=1
#cur.excute(insert_bm,(1,"DEV"))


#-----------3.3查询数据--------------
# select_bm = "select * from bm;"
# cur.execute(select_bm) #显示所有数据
# print(cur.fetchone()) #抓取第一条数据
# print(cur.fetchmany(2))#从游标下方抓取两个,第二,三条
# print(cur.fetchall())#从游标下方抓取剩下的所有4,5
#如果想要指定的数据,需要在select_bm = "select * from bm;"详细描写

#-----------3.4修改数据--------------
update_bm = "update bm set bm_name=%s where bm_id = %s"
cur.executemany(update_bm,[("OPS",1),("DEV",2)])
#-----------3.5 删除数据--------------
# delete_bm =" delete from bm where bm_id=%s;"
# cur.executemany(delete_bm,[1,2,3,4,5])

#4.提交事务以及关闭资源
conn.commit()
cur.close()
conn.close()

练习 :员工表 (EMPLOYEE) 相关操作

需求

  1. 员工表有 FIRST_NAME VARCHAR(20),LAST_NAME VARCHAR(20),AGE INT,SEX VARCHAR(1),INCOME FLOAT字段

  2. 使用 PyMySQL 创建该表

  3. 使用 PyMySQL 添加以下三条数据

    1. 'Mac', 'A', 20, 'M', 20000
    2. 'Tom', 'B', 20, 'F', 30000
    3. 'Bob', 'C', 20, 'M', 40000
  4. 使用 PyMySQL 查询所有用户信息,并打印结果

  5. 将 FIRST_NAME 为 Mac 的用户工资改成 10000

  6. 删除 FIRST_NAME 为 Tom 的用户信息

    import pymysql
    
    # 打开数据库连接
    
    db = pymysql.connect(
    
        host='127.0.0.1', 
    
        port=3306, 
    
        user='root',
    
        db='tedu1', 
    
        charset='utf8'
    
    )
    
    # 使用 cursor() 方法创建一个游标对象 cursor
    
    cur = db.cursor()
    
    
    ##########################################################
    
    # 创建表
    
    sql = """CREATE TABLE EMPLOYEE (
    
        FIRST_NAME  VARCHAR(20) NOT NULL,
    
        LAST_NAME  VARCHAR(20),
    
        AGE INT,  
    
        SEX VARCHAR(1),
    
        INCOME FLOAT 
    
    )"""
    
    cur.execute(sql)
    
    ##########################################################
    
    # SQL 插入语句
    
    sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
    
             LAST_NAME, AGE, SEX, INCOME)
    
             VALUES (%s, %s, %s, %s, %s)"""
    
    cur.executemany(  # executemany(), 执行sql语句, 同时插入多条记录
    
        sql, [
    
            ('Mac', 'A', 20, 'M', 20000), 
    
            ('Tom', 'B', 20, 'F', 30000), 
    
            ('Bob', 'C', 20, 'M', 40000)
    
        ]
    
    )
    
    db.commit()
    
    ##########################################################
    
    sql = "SELECT * FROM EMPLOYEE"
    
    cur.execute(sql)
    
    result = cur.fetchone()
    
    print(result)
    
    result2 = cur.fetchmany(2)
    
    print(result2)
    
    ##########################################################
    
    sql = 'UPDATE EMPLOYEE SET INCOME=%s WHERE FIRST_NAME=%s'
    
    cur.execute(sql, (10000, 'Mac'))
    
    db.commit()
    
    ##########################################################
    
    sql = 'DELETE FROM EMPLOYEE WHERE FIRST_NAME=%s'
    
    cur.execute(sql, ("Tom",))
    
    db.commit()
    
    # 关闭数据库连接
    
    cur.close()
    
    db.close()

    Redis模块

    Redis是一种基于内存的数据结构存储系统,广泛应用于缓存、消息队列、计数器、实时排行榜等场景。Python提供了redis模块,可以方便地在Python中使用Redis。

    连接

    使用redis模块连接Redis服务器需要提供服务器的IP地址和端口号。如果Redis服务器没有密码验证,则可以直接使用redis模块提供的Redis类进行连接;如果Redis服务器开启了密码验证,则需要使用redis模块提供的StrictRedis类,并提供密码参数

    # 连接Redis服务器(无密码验证)
    r = redis.Redis(host='127.0.0.1', port=6379)
    # 连接Redis服务器(有密码验证)db=0~15
    sr = redis.StrictRedis(host='127.0.0.1', port=6379, password='password')

    数据类型

    Redis支持多种数据类型,包括字符串、哈希表、列表、集合和有序集合等。redis模块提供了对应的类和方法,可以方便地操作这些数据类型。

    字符串

    字符串是最基本的数据类型,可以存储任何类型的数据。redis模块提供了set和get方法,用于设置和获取字符串值

import pymysql,redis
#1.预热  2.插入
class DetaUtil:
    def __init__(self): #创建mysql以及redis的连接对像
        try:
            self.conn=pymysql.connect(
                host="192.168.88.11",port=3306,
                user="root",password="123456",
                db="tedu_test",charset="utf8")
        except Exception as e:
            print("mysql连接失败!!")
            print("reason:",e)
            exit() #退出程序

        try:#创建redis连接对象
            self.r=redis.Redis(host="192.168.88.11",port=6379)
        except Exception as e:
            print("redis连接失败!")
            print("reason:",e)
            exit() #退出程序



    def get_data(self, stu_id): #数据查询&&数据预热
            #1.查询redis中没有要的数据
            stu_info=f"stu_{stu_id}"
            data=self.r.hgetall(stu_info)
            if len(data) !=0:#redis中有数据
                self.r.expire(stu_info,100) #重新设置过期时间
                print(data)
                print("select by redis...")
                return data

            #2.查询数据库,将查到的数据库缓存到redis中,返回数据
            #2.1有,从缓存中返回想要的数据
            #2.2没有,查询数据库mysql,将查到的数据缓存到redis中,返回数据
            cur=self.conn.cursor() #获取游标
            s_stu="select * from tedu_student where stu_id=%s;"
            cur.execute(s_stu,stu_id) #stu_data:tuple
            stu_data=cur.fetchone() #(1001, 'zs', datetime.date(1990, 12, 15), '13344445555')
            print(stu_data)
            cur.close()

            #元组:()——> 集合
            #将查询的数据添加至缓存进行预热
            stu_dict={"stu_name":stu_data[1],
                      "stu_birth": str(stu_data[2]),
                      "stu_phone": stu_data[3], }
            # 当在 Redis 集合中插入日期时,需要将日期转换为字符串的原因是
            # Redis保存数据时只支持字符串类型。将日期转换为字符串后,可以将其作为集合的元素进行存储和操作。
            stu_info = f"stu_{stu_id}"
            stu_data=self.r.hmset(stu_info,stu_dict)
            self.r.expire(stu_info,100) #添加100s过期时间
            print(stu_data)
            print("select by mysql...")

    #插入数据
    def insert_data(self,id,name,birth,phone):
        cur=self.conn.cursor()
        i_stu = "insert into tedu_student values(%s,%s,%s,%s) "
        try:
            cur.execute(i_stu,(id,name,birth,phone))
        except Exception as e:
            print("SQL error...")
            print("reason:",e)
        finally:
            cur.close()
            self.conn.commit()


if __name__ == '__main__':
    d1=DetaUtil()
    #1.首先插入数据
    # d1.insert_data("1005","heh","19991212","133333333")
    d1.insert_data("10","heh","19991212","133333333")
    #2.数据预热---mysql
    #d1.get_data(1005)
    #3.redis ---> 预热成功
    d1.get_data(1005)

爬虫:

get post head delete

更新:patch(补丁) put(全量)

抓取文件图片:

import requests
# def download(url,path): #下载:1.下载到哪里 2.资源在哪里
#     with open(path,mode="wb") as fw:
#         resp=requests.get(url)
#         fw.write(resp.content)
# download("https://cdn.tmooc.cn/bsfile//imgad///5706defebbff4fdfb0a19b70d6bef77b.png","/tmp/image.jpg")

#User-Agent:用户代理,请求头的一部分
#请求头字典显示
header = {"User-Agent":"Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0"}
resp=requests.get("https://www.jianshu.com/",headers=header)#respose:响应
print(resp.text)#以文本格式查看响应数据
#
# resp1=requests.get("https://cdn.tmooc.cn/bsfile//imgad///5706defebbff4fdfb0a19b70d6bef77b.png")
# print(resp1.content)#以二进制格式查看响应数dd#linux中命令eog /tmp/image.jpg 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值