python笔记:mysql、redis *** 作方法

python笔记:mysql、redis *** 作方法,第1张

概述模块安装:数据 *** 作用到的模块pymysql,需要通过pipinstallpymysql进行安装。redis *** 作用的模块是redis,需要通过pipinstallredis进行安装。

模块安装:

数据 *** 作用到的模块pyMysqL,需要通过pip install pyMysqL进行安装。

redis *** 作用的模块是redis,需要通过pip install redis进行安装。

检验是否安装成功:进入到Python命令行模式,输入import pyMysqL、 import redis ,无报错代表成功;

MysqL *** 作方法如下:

查询数据:fetchone、fetchmany(n)、fetchall()

import pyMysqL#建立MysqL连接,ip、端口、用户名、密码(passwd,不能写成其他,例如:pwd或者p,否则报错)、库名conn = pyMysqL.connect(host='127.0.0.1',user='root',passwd='123456',db='szz',port=3306,charset='utf8')#创建游标cur = conn.cursor(cursor=pyMysqL.cursors.DictCursor) #指定cursor的类型为字典,返回结果类型是字典,不再是元组#执行sql,返回值是int,查询出来的结果有几条cur.execute('select * from test')#获取第一条数据,游标cur所在的位置为1,游标从0开始,查询结果类型为:字典row_1 = cur.fetchone()cur.scroll(0,mode='absolute')  #将游标移动到初始位置#获取前n行数据row_2 = cur.fetchmany(n)cur.scroll(0,mode='absolute')  #将游标移动到初始位置#获取所有数据,返回结果类型是:List,里面元素是字典row_3 = cur.fetchall()cur.scroll(0,mode='absolute')  #将游标移动到初始位置print(row_2)#关闭游标cur.close()#关闭连接conn.close()

增加、更新、删除数据

import pyMysqL#建立MysqL连接conn = pyMysqL.connect(host='127.0.0.1',charset='utf8')#创建游标cur = conn.cursor(cursor=pyMysqL.cursors.DictCursor) #指定cursor的类型为字典,返回结果类型是字典,不再是元组#执行sqlsql = 'insert into test values(5,"断点","e10adc3949ba59abbe56e057f20f883e")'sql_update = 'update test set name="薛之谦" where ID=2 'sql_del = 'delete from test where ID = 3'cur.execute(sql_del)#insert、update、delete语句需要进行commit,否则无法保证修改或者新建的数据conn.commit()#关闭游标cur.close()#关闭连接conn.close()

cursor的相对、绝对位置移动

import pyMysqL#建立MysqL连接conn = pyMysqL.connect(host='192.168.3.66',charset='utf8')#创建游标cur = conn.cursor(cursor=pyMysqL.cursors.DictCursor) #指定cursor的类型为字典,返回结果类型是字典,不再是元组num = cur.execute('select * from testlhl')print(num)                      #返回结果是int类型row_1 = cur.fetchone()       # 此时游标的位置在1,数据库取值从0下标开始,获取数据库第一条数据cur.scroll(2,mode='absolute')   #absolute绝对位置,直接是将游标从0位置移动到指定的位置2row_2 = cur.fetchone()       #读取数据库第3条数据,游标在3位置cur.scroll(2,mode='relative')   #relative相对位置,相对于游标当前所在位置,进行移动,移动1位,游标在4位置,若相对移动的位置超过下标,则报out of rangerow_3 = cur.fetchone()       #读取第5条数据#关闭游标cur.close()#关闭连接conn.close()

MysqL的增删改查公共方法,代码如下:

def getconn(host,user,passwd,db,sql,charset='utf8'):  conn = pyMysqL.connect(host=host,user=user,passwd=passwd,port=port,db=db,charset=charset) #建立连接  cur = conn.cursor(cursor=pyMysqL.cursors.DictCursor)    #建立游标并指定游标类型  cur.execute(sql)                      #执行sql  if sql.startswith('select'):                #判断sql是否是select    res = cur.fetchone()  else:    conn.commit()                      #insert\delete\update语句执行完毕后需要进行commit    res = 88  cur.close()                         #关闭游标  conn.close()                        #关闭连接  return res

redis *** 作方法如下:

key的类型是string,进行set *** 作,模式{key,value},如下:

import redisdb = 0#连接redis,password不简写(否则或报错),db若不写,则默认 *** 作db0conn_redis = redis.Redis(host='127.0.0.1',port=6379,password='123456',db=db)#给redis添加值,传值方式是key-value,key不可重复,value的形式尽量是string,也可以传List、字典,redis内存放的是字节res = conn_redis.set('name','testredis')#print(res)  #返回值是布尔类型,set成功,则返回trueconn_redis.set('days','[10,4,5,12,44]')#set key值到redis内,且可以设置过期时间,10sresult = conn_redis.setex('session','abcder1233@sdfrr',10)  #单位是sprint(result)  #返回值是布尔类型,set成功,则返回true#批量插入redis,可以写入多个key-valyeconn_redis.mset(a='xiaohei',b='xiaobai',c='xiaohuang') #设置key时,可以设置文件夹,user文件夹,key:test,value:hahaconn_redis.set('user:test','haha')

获取redis内的数据,通过key值进行获取

import redisimport Jsondb = 0#连接redis,db=db)#获取redis的值,返回结果类型是bytesres = conn_redis.get('abcd')#使用decode()将bytes类型转换为字符串:输出>>>>>testredisnew_res = res.decode()#使用Json的loads,将Json串(字符串)转换为字典dic_res = Json.loads(new_res)#获取不存在的key,返回结果为Noneres1 = conn_redis.get('asdfg')print(res1.decode())    #输出>>>>>>'nonetype' object has no attribute 'decode'#获取所有的keys,且循环遍历进行输入,使用decode()转换为字符串List_keys = conn_redis.keys()for key in List_keys:  print(key.decode())#获取所有的key中以n开头的key,返回结果类型是List,元素类型是bytes 输出>>>>>[b'nbeee',b'name',b'nest']print(conn_redis.keys('n*'))

删除redis内的值,通过key删除

import redisdb = 0#连接redis,password不简写(否则或报错),db若不写,则默认 *** 作db0conn_redis = redis.Redis(host='192.168.3.66',db=db)#删除存在的key,删除key后,redis内不存在该key,返回结果为1,删除了一个keyres = conn_redis.delete('a')#删除不存在的key,返回结果为0,没有删除keyres1 = conn_redis.delete('d')#删除多个key,返回结果n, 删除了几个key就返回数字几asdf = conn_redis.delete('a','b','c')print(asdf)

key的类型是hash,进行set *** 作,模式:{key,{key1,value}}如下

import redisdb = 0#连接redis,db=db)#hash类型的key,模式{name,{key,value}},里面key不能重复,返回值为intres = conn_redis.hset('user_session','lhl','sunny')#hash类型的key,添加值时也可以设置文件夹conn_redis.hset('session:redis_test','age',18)

key的类型是hash,进行get *** 作,如下

import redisdb = 0#连接redis,db=db)#获取hash类型中的某个name下的某个key对应的value,获取指定name里面的key的值,返回结果类似是bytesres = conn_redis.hget('user_session','week')#获取hash类型中name里面所有的key,返回结果是字典>>>>>输出:{b'test': b'sunny',b'week': b'sunny'}all = conn_redis.hgetall('user_session')

key的类型是hash,进行delete *** 作,如下

import redisdb = 0#连接redis,db=db)#hash类型的key,删除整个key,delete(name),返回结果为1res = conn_redis.delete('user_session')#hash类型的key,删除指定name里的key,若删除的key或者name不存在,则返回0res = conn_redis.hdel('user_session','week')

redis的set、get公共 *** 作方法如下

def opRedis(host,password,key,value=None,db=0):   #redis *** 作时需要传入key\value  conn_redis = redis.Redis(host=host,password=password,db=db)  #获取redis连接  if value:              #判断value是否传值,如果不为None,则是set    conn_redis.setex(key,value,60)  #设置key的过期时间,60s    res = 88  else:    res = conn_redis.get(key).decode()   #将从redis内读取的值,由bytes转换为字符串  return res

以上这篇python笔记:MysqL、redis *** 作方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的python笔记:mysql、redis *** 作方法全部内容,希望文章能够帮你解决python笔记:mysql、redis *** 作方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1202043.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存