zoukankan      html  css  js  c++  java
  • 10_Python_数据库操作(MySQL、Mongodb、Redis)

    1、MySQL 数据库

    1.1、安装PyMysql

    pip install PyMysql
    

    1.2、使用 PyMySQL

    1.2.1、连接数据库

    import pymysql
    
    
    def connectdb():
        print('连接到mysql服务器...')
        # 打开数据库连接
        # 用户名:hp, 密码:Hp12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库TESTDB,并在TESTDB数据库中创建好表Student
        db = pymysql.connect(
            host='localhost',
            user='root',  # 用户名 :test
            password='123456',  # 密 码 :123456
            db='test',  # 数据库 :test
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor)
        print('连接上了!')
        return db
    

    1.2.2、获取数据库游标

    my_cousor = db.cursor()
    #获取数据库游标对象
    

    1.2.3、创建数据表

    def createtable(db):
        # 使用cursor()方法获取操作游标 
        cursor = db.cursor()
    
        # 如果存在表Sutdent先删除
        cursor.execute("DROP TABLE IF EXISTS Student")
        sql = """CREATE TABLE Student (
                ID CHAR(10) NOT NULL,
                Name CHAR(8),
                Grade INT )"""
    
        # 创建Sutdent表
        cursor.execute(sql)
        
    
    if __name__ == '__main__':
        db = connectdb()
        createtable(db)
    

    1.2.4、执行SQL语句(增加、修改、删除)

    def sql_commit(db, sql):
        '''执行SQL语句'''
        # 使用cursor()方法获取操作游标
        cursor = db.cursor()
    
        try:
            # 执行sql语句
            cursor.execute(sql)
            # 提交到数据库执行
            db.commit()
            print('post:' + str(sql))
        except:
            # 如果发生错误,执行回滚操作
            print('Error:' + str(sql))
            db.rollback()
    
    
    
    if __name__ == '__main__':
        # 1、插入数据
        sql_insert_01 = "INSERT INTO Student(ID, Name, Grade)  VALUES ('%s', '%s', '%d')" % ('001', 'HP', 60)
        sql_insert_02 = "INSERT INTO Student VALUES ('001', 'CZQ', 70), ('007', 'TEST', 100)"
    
        # 2、更新数据
        sql_update = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003')
    
        #3、删除数据
        sql_delete = "DELETE FROM Student WHERE Grade = '%d'" % (70)
    
        db = connectdb()
        sql_commit(db, sql_delete)
    

    1.2.5、查询数据(单条、多条)

    fetchone() :

    • 返回单个的元组,也就是一条记录(row),如果没有结果 , 则返回 None。
    • 如果查询出多条数据,将只取最上面的第一条结果,返回单个元组,多次循环使用,将会依次取得下一条结果,直到为空。

    fetchall() :

    • 返回多个元组,即返回多条记录(rows),如果没有结果,则返回 ()。
    def select_one(db, sql):
        '''查询单条数据、或者返回多条数据的第一条'''
        # 使用cursor()方法获取操作游标
        cursor = db.cursor()
        try:
            # 执行sql语句
            cursor.execute(sql)
            results = cursor.fetchone()
            print(results)
        except:
            # 如果发生错误,显示提示
            print('Error:' + str(sql))
    
    
    def select_all(db, sql):
        '''查询多条数据'''
        # 使用cursor()方法获取操作游标
        cursor = db.cursor()
        try:
            # 执行sql语句
            cursor.execute(sql)
            results = cursor.fetchall()
            for i in results:
                print(i)
        except:
            # 如果发生错误,显示提示
            print('Error:' + str(sql))
    
    
    if __name__ == '__main__':
        sql_select = "SELECT * FROM Student"
        db = connectdb()
        select_all(db, sql_select)
    

    1.2.6、关闭数据库

    def closedb(db):
        '''关闭数据库'''
        db.close()
    

    2、Mongodb 数据库

    2.1、安装PyMysql

    pip install pymongo
    

    2.2、使用 pymongo

    2.2.1、连接mongodb数据库

    import pymongo
    
    '''连接MongoDB数据库的两种方法'''
    
    #方法1:
    client = pymongo.MongoClient(host='localhost', port=27017)
    #方法2:
    client = pymongo.MongoClient('mongodb://localhost:27017/')
    

    2.2.2、指定数据库

    '''指定数据库的两种方法'''
    
    # 数据库名:test_mongodb
    #方法1:
    db = client.test_mongodb
    #方法2:
    db = client['test_mongodb']
    
    

    2.2.3、指定集合

    • MongoDB的每个数据库又包含许多集合(collection),它们类似于关系型数据库中的表。
    '''指定集合的两种方法'''
    
    # 集合名:test_table
    #方法1:
    collection = db.test_table
    #方法2:
    collection = db['test_table']
    

    2.2.4、插入数据

    • insert_one():插入单条数据
    • insert_many():插入多条数据
    import pymongo
    
    collection = pymongo.MongoClient(host='localhost', port=27017)['test_mongodb']['test_table']
    
    test_01 = {
        'number': '1111',
        'name': 'test_01',
        'age': 20,
    }
    
    test_02 = {
        'number': '2222',
        'name': 'test_02',
        'age': 20,
    }
    
    '''插入单条数据'''
    result = collection.insert_one(test_01)
    print(result.inserted_id)
    
    '''插入多条数据'''
    result = collection.insert_many([test_01, test_02])
    print(result.inserted_ids)
    

    2.2.5、查询数据:find()、find_one()

    • find_one()查询得到的是单个结果。
    • find()则返回一个生成器对象。
    import pymongo
    
    collection = pymongo.MongoClient(host='localhost', port=27017)['test_mongodb']['test_table']
    
    '''查询单条数据'''
    result_1 = collection.find_one({'name': 'test_02'})
    print(result_1)
    
    '''查询多条数据'''
    result_2 = collection.find({'age': 20})
    for i in result_2:
        print(i)
    
    

    2.2.6、mongodb的条件操作符

    #    (>)  大于 - $gt
    #    (<)  小于 - $lt
    #    (>=)  大于等于 - $gte
    #    (<= )  小于等于 - $lte
    
    #在20-23范围内
    {'age': {'$in': [20, 23]}}
    
    #不在20-23范围内
    {'age': {'$nin': [20, 23]}}
    
    
    '''查询 age > 20 的数据'''
    result_2 = collection.find({"age":{"$gt":20}})
    for i in result_2:
        print(i)
    

    2.2.7、数据计数:count()

    • 要统计查询结果有多少条数据,可以调用 count()方法。
    '''统计所有的数据'''
    
    result = collection.find().count()
    print(result)
    

    2.2.8、数据排序:sort()

    • 在MongoDB中使用sort()方法对数据进行排序,sort()方法可以通过参数指定排序的字段,并使用 1 和 -1 来指定排序的方式。
    • 其中 1 为升序,-1为降序。
    '''按照name字段的升序进行排序'''
    
    result = collection.find().sort('name', 1)
    for i in result:
        print(i)
    
    

    2.2.9、数据更新:update()

    • 使用update()方法,指定更新的条件和更新后的数据即可。
    import pymongo
    
    collection = pymongo.MongoClient(host='localhost', port=27017)['test_mongodb']['test_table']
    
    # 首先查询出对应的数据
    condition = {'name': 'test_02'}
    result = collection.find_one(condition)
    # 更新后的数据
    result['age'] = '100'
    # 使用update() 方法进行更新
    result_2 = collection.update(condition, result)
    

    2.2.10、删除数据:remove()

    result = collection.remove({'name': 'test_02'})
    print(result)
    

    limit和skip

    2.2.11、limit()、skip()

    • limit()方法用来读取指定数量的数据。
    • skip()方法用来跳过指定数量的数据。
    '''跳过2条数据'''
    result = collection.find().skip(2)
    
    '''读取6条数据'''
    result = collection.find().limit(6)
    

    3、Redis 数据库

    3.1、安装 redis

    pip install redis
    

    3.2、使用 redis

    3.2.1、连接池

    import redis
    
    pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True,db=5)
    r = redis.Redis(connection_pool=pool)
    

    3.2.2、插入数据

    • set(name, value, ex=None, px=None, nx=False, xx=False)

    参数:

    • ex,过期时间(秒)
    • px,过期时间(毫秒)
    • nx,如果设置为True,则只有name不存在时,当前set操作才执行
    • xx,如果设置为True,则只有name存在时,当前set操作才执行
    r.set('name','老王')
    

    3.2.3、获取数据

    r.get('name')
    

    未完。。。。

  • 相关阅读:
    JavaWeb网上商城项目中用户注册,使用MailServer和FoxMail搭建本地邮件服务器
    myeclipse编码问题
    Date日期类型的绑定
    springmvc学习之jdk版本,tomcat版本,spring版本
    mybatis-ehcache整合中出现的异常 ibatis处理器异常(executor.ExecutorException)解决方法
    .net里面<app.config>中value值不能填写特殊符号问题
    sqldeveloper中Excel数据的导入与导出
    IntelliJ IDEA 2019.2最新版本免费激活码(转)
    sqlserver 的一些小总结
    SQL 跨数据库同步数据 、跨数据库跨更新数据
  • 原文地址:https://www.cnblogs.com/jasontang369/p/9248884.html
Copyright © 2011-2022 走看看