zoukankan      html  css  js  c++  java
  • python基础六--操作数据库

    操作数据库模块:mysql的pymysql和redis的redis ,参考http://www.nnzhp.cn/blog/archives/402

    1、操作mysql

    import pymysql
    
    conn=pymysql.connect(host='192.168.160.3',user='root',port=3306,passwd='123456',db='hqtest',charset='utf8')   #建立数据库连接     #关键字传参
    
    couser=conn.cursor() #在连接上建立一个游标
    sql='insert into hq(username,password) value("hq","25906028d04ba0563447f41dccb3c4cf")'
    couser.execute(sql2)
    conn.commit()   #提交,insert、update、delete必须commit才能生效
    
    sql2='select * from hq'
    couser.execute(sql)
    print(couser.fetchall())  # 获取所有数据
    couser.scroll(1,mode='absolute')   #移动游标,绝对的
    print(couser.fetchone())   #每执行一次 获取一列数据
    couser.scroll(0,mode='relative')   #移动游标,相对的
    print(couser.fetchone())   #每执行一次 获取一列数据
    
    couser=conn.cursor(cursor=pymysql.cursors.DictCursor)  #指定字典类型cursor
    sql3='select * from hq'
    couser.execute(sql3)
    print(couser.fetchall())
    
    couser.close()   #关闭游标
    conn.close()   #关闭连接

    2、操作redis

    import redis,json
    
    r=redis.Redis(host='192.168.160.3',port=6379,db=0,password='123456')
    
    # redis里面存的都是字符串;redis里面获取到的数据都是bytes类型的
    
    # string类型的key
    r.set('name',[1,2,3,4])
    name = r.get('name')
    print(name.decode())# 要使用.decode方法给它转成字符串才能继续操作
    new_name = json.loads(name.decode())# list和字典
    print(type(new_name))
    r.setex('eee','hahaha',15)# 可以设置key的失效时间
    print(r.get('hahahaahahahasdfsdfsd'))# get不存在的key,就是返回None
    r.mset(nhy='hahahaha',eee_age=19999) # 批量添加,排量set值时候用
    r.delete('eee') # 删除某个key
    print(r.keys('*n*')) # 获取所有的key
    
    # 哈希类型的key
    r.hset('user_session','eee','sdfjksdjflksfsdfsdfsfs')
    r.hset('user_session','ooo','sdfjksdjflksfsdfsdfsfs')
    print(r.hget('user_session','eee'))# 获取指定name里面k的值
    print(r.hgetall('user_session'))# 获取哈希类型里面所有的值
    r.hdel('user_session','eee')#删除指定的key
    r.delete('user_session')#把整个key全删掉
    
    # 创建文件夹
    r.set('user:eee','haha') #创建文件添加string类型的key
    r.set('user:ooo','hehe')
    r.hset('session:qwert','www','12345')  #创建文件添加hash类型的key
  • 相关阅读:
    Python入门教程 超详细1小时学会Python
    K最近邻(KNN,k-Nearest Neighbor)准确理解
    K最近邻(KNN,k-Nearest Neighbor)准确理解
    如何区分数据科学家,数据工程师与数据分析师
    如何区分数据科学家,数据工程师与数据分析师
    【BZOJ】1003 Cards
    TinySpring分析二
    Tomcat 系统架构与设计模式,第 1 部分: 工作原理
    MySQL中使用INNER JOIN来实现Intersect并集操作
    jqPaginator-master | kkpager-master 这两个分页插件的使用方法
  • 原文地址:https://www.cnblogs.com/eeoo/p/7101161.html
Copyright © 2011-2022 走看看