• Python小练习_将数据库中表数据存到redis里


    # ##练习:将xxx数据库中my_user表中数据存到redis里面
    # 分析: pymysql、json、redis
    # 1.连接数据库,查到数据库里面所有的数据,游标类型要用pymysql.cursor.Dictcour
    # 2.查到所有数据[{"id":1,"passwd":"49487dd4f94008a6110275e48ad09448","username":"6j","is_admin":1}]
    # 3.循环这个list,取到username,把username当作key
    # 4.再把这个小字典转成json,存进去就ok


     1 import json,redis
     2 def my_db(table_name):
     3     import pymysql
     4     coon =pymysql.connect(
     5         user='xxx',passwd='123456',host='xxx.xxx.xx.xxx',port=3306,
     6         db='xxx',charset='utf8'
     7     )
     8     cur = coon.cursor(cursor=pymysql.cursors.DictCursor) #建立游标,指定cursor类型返回的是字典
     9     # cur = coon.cursor()
    10     sql = 'select * from %s;'%table_name
    11     cur.execute(sql)
    12     if sql.strip()[:6].upper()=='SELECT':
    13         res = cur.fetchall()
    14     cur.close()
    15     coon.close()
    16     return res
    17 
    18 all_date = my_db('my_user')
    19 r = redis.Redis(host='xxx.xxx.xxx.xxx',password='123456',db=0)  #端口号默认6379
    20 # print(all_date)
    21 
    22 for date in all_date:
    23     # print(date)
    24     key = date.get('username')
    25     # print(key)
    26     value = json.dumps(date)
    27     # print(value)
    28     r.hset('stu_info_6j',key,value)

     简洁版:

     1 import pymysql,json,redis
     2 r = redis.Redis(host='xxx.xxx.xx.xxx',password='123456',db=1,port=6379)
     3 conn = pymysql.connect(host='xxx.xxx.xx.xxx',user='xxx',passwd='123456',db='xxx',charset='utf8')
     4 cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
     5 cur.execute('select * from my_user;')
     6 all_data = cur.fetchall()
     7 for data in all_data:
     8    k = data.get('username')
     9    r.hset('stu_info_nhy',k,json.dumps(data))
    10 cur.close()
    11 conn.close()
  • 相关阅读:
    分库分表的技术演进
    Mybatis传递多个参数
    tomcat实现热部署的配置
    名为'<Cursor Name>'的游标已存在
    ABP示例程序-使用AngularJs,ASP.NET MVC,Web API和EntityFramework创建N层的单页面Web应用
    ABP官方文档翻译 10.1 ABP Nuget包
    ABP官方文档翻译 9.3 NHibernate集成
    ABP官方文档翻译 9.2 Entity Framework Core
    ABP官方文档翻译 9.1 EntityFramework集成
    ABP官方文档翻译 8.2 SignalR集成
  • 原文地址:https://www.cnblogs.com/jessica-test/p/9004774.html
Copyright © 2020-2023  润新知