美文网首页
各种数据库与Python之间的交互

各种数据库与Python之间的交互

作者: 未央_m | 来源:发表于2018-10-22 21:55 被阅读0次

    一、MySQL与Python的交互

    - 安装
        pip3 install pymysql
    
    - 使用
    import pymysql
    
    # 链接数据库
    db = pymysql.Connect(host='127.0.0.1', port=3306, user='root', password='123456', database='test08', charset='utf8')
    # 数据库游标
    cursor = db.cursor()
    
    # 查询数据
    db.begin()
    cursor.execute("select * from students_info;")
    db.commit()
    # 获取所有数据
    print(cursor.fetchall())
    # 获取一个,根据下标取对应的数据
    print(cursor.fetchall()[0])
    # 注: 不能同时使用,因为游标会往后移动
    
    # 插入数据
    db.begin()
    cursor.execute("insert into students_info values ('2000', '老李', '18', '男', '广东深圳', '1703', '89', '90', '81');")
    db.commit()
    
    # 更新数据
    db.begin()
    cursor.execute("update students_info set class='1807' where id=2000")
    db.commit()
    
    # 删除数据
    db.begin()
    cursor.execute("delete from students_info where id=2000")
    db.commit()
    

    二、MongoDB与Python的交互

    - 安装
    pip3 install pymongo
    
    - 使用
    import pymongo
    from pymongo import  MongoClient
    from bson.objectid import ObjectId
    
    #1.建立连接
    #创建MongoClient的对象
    #方式一
    #特点:可以连接默认的主机和端口号
    #client = MongoClient()
    #方式二
    #明确指明主机和端口号
    #client = MongoClient('localhost',27017)
    #client = MongoClient(host='localhost',port=27017)
    #方式三
    #使用MongoDB URI的
    client = MongoClient('mongodb://localhost:27017')
    
    #2.获取数据库
    #MongoDB的一个实例可以支持多个独立的数据库
    #可以通过MongoClient的对象的属性来访问数据库
    #方式一
    db = client.test
    print(db)
    #方式二
    #db = client['test']
    
    #3.获取集合
    #集合是存储在MongoDb中的一组文档,可以类似于MySQl中的表
    #方式一
    collection = db.stuents
    #方式二
    #collection = db['students']
    """
    注意:
    MongoDB中关于数据库和集合的创建都是懒创建
    以上的操作在MongoDB的服务端没有做任何操作
    当第一个文档被插入集合的时候才会创建数据库和集合
    """
    
    #4.文档
    #在pymongo中使用字典来表示文档
    student1 = {
        'id':'20180101',
        'name':'jack',
        'age':20,
        'gender':'male'
    }
    
    #5.插入文档
    #5.1insert()
    #插入单条数据
    #注意:MongoDb会自动生成一个ObjectId,insert函数的返回值为objectid
    result = collection.insert(student1)
    print(result)
    
    #插入多条数据
    student2 = {
        'id':'20180530',
        'name':'tom',
        'age':30,
        'gender':'male'
    }
    student3 = {
        'id':'20180101',
        'name':'bob',
        'age':18,
        'gender':'male'
    }
    #result = collection.insert([student2,student3])
    
    #6.查询文档
    #6.1
    #find_one()
    result = collection.find_one({'name':'jack'})
    print(type(result))    #<class 'dict'>
    print(result)
    
    #6.2find()
    #需求:查询年龄为20的数据
    results = collection.find({'age':20})
    print(results)
    #Cursor相当于是一个生成器,只能通过遍历的方式获取其中的数据
    for r in results:
        print(r)
    
    #6.3其他用法
    #a.count()
    #统计所有数据的条数
    count1 = collection.find().count()
    #统计制定条件的数据条数
    count1 = collection.find({'age':20}).count()
    
    #7.更新文档
    #7.1update()
    conditon = {'name':'jack'}
    student = collection.find_one(conditon);
    student['age'] = 30
    result = collection.update(conditon,student)
    
    #7.2update_one()
    conditon = {'name':'jack'}
    student = collection.find_one(conditon);
    student['age'] = 30
    result = collection.update_one(conditon,{'$set':student})
    print(result.matched_count,result.modified_count)
    
    #7.3update_many()
    #查询年龄大于20的数据,然后讲年龄增加1
    conditon = {'age':{'$gt':20}}
    result = collection.update_one(conditon,{'$inc':{'age':1}})
    print(result.matched_count,result.modified_count)
    
    #8.删除文档
    #8.1 remove()
    #将符合条件的所有的数据全部删除
    result = collection.remove({'name':'rose'})
    
    #8.2 delete_one()
    result = collection.delete_one({'name':'rose'})
    
    #8.3 delete_many()
    result = collection.delete_many({'name':'rose'})
    
    

    备注: 默认MongoDB是绑定127.0.0.1,连接远程是连接不了的。
    编辑MongoDB配置文件: sudo vi /etc/mongodb.conf
    找到 bind_ip = 127.0.0.1 改为 bind_ip = 0.0.0.0

    三、Redis与Python交互

    - 安装
      pip3 install redis
    
    - 说明
      from redis import StrictRedis
      这个模块中提供了StrictRedis对象(Strict严格),用于连接redis服务器,并按照不同类型提供 了不同方法,进行交互操作
      StrictRedis对象方法:
      通过init创建对象,指定参数host、port与指定的服务器和端口连接,host默认为localhost,port默认为6379,db默认为0 sr = StrictRedis(host='localhost', port=6379, db=0)
    
    - 使用
    from redis import  *
    
    # 创建一个StrictReids对象,与redis服务器建立连接
    sr = StrictRedis(host='localhost', port=6379, db=0)
    
    #1.增
    try:
        result = sr.set('py1', 'gj')
        # result如果为true,则表示添加成功
        print(result)
    except Exception as e:
        print(e)
    
    #2.删
    #result = sr.delete('py1')
    #print(result)
    
    #3.改
    result = sr.set('py1','he')
    
    #4.查
    #如果建不存在,则返回None
    result = sr.get('py1')
    
    #5.获取建
    result = sr.keys()
    
    

    备注: 默认redis是绑定127.0.0.1,连接远程是连接不了的。
    编辑redis配置文件: sudo vi /etc/redis/redis.conf
    找到 bind 127.0.0.1 改为 bind 0.0.0.0

    相关文章

      网友评论

          本文标题:各种数据库与Python之间的交互

          本文链接:https://www.haomeiwen.com/subject/ysfnzftx.html