美文网首页
python 对数据库基本操作方法

python 对数据库基本操作方法

作者: 9016 | 来源:发表于2021-05-18 07:13 被阅读0次

    以MYSQL为例。

    import pymysql
    import redis
    
    
    def conn(u, p, h, o, d):
        # 连接数据库(MYSQL)
        # u/用户名: str  'edaijia'
        # p/登录密码: str  '12345678'
        # h/数据库服务器IP: str  '121.40.43.10'
        # o/数据库服务器端口: num  3306
        # d/数据库名: str  'db_report'
        try:
            global thisDb
            global connStr
            connStr = pymysql.connect(
                user=u,
                passwd=p,
                host=h,
                port=o,
                db=d)
            connStr.autocommit(True)
            thisDb = connStr.cursor()
        except Exception as err:
            print('数据库无法连接: %s' % err)
    
    
    def query(sqlStr):
        # 返回数据库查询结果
        # sqlStr/被执行SQL: str  'select * from user order by created desc limit 1'
        try:
            thisDb.execute(sqlStr)
            # connStr.commit()
            results = thisDb.fetchall()
            return results
        except Exception as err:
            print('SQL执行错误: %s' % err)
    
    
    def execute(sqlStr):
        # 返回执行SQL后影响行数
        # sqlStr/被执行SQL: str  'select * from user order by created desc limit 1'
        try:
            results = thisDb.execute(sqlStr)
            connStr.commit()
            # results = thisDb.fetchall()
            return results
        except Exception as err:
            print('SQL执行错误: %s' % err)
    
    
    def close():
        try:
            thisDb.close()
        except Exception as err:
            print('无连接可关闭: %s' % err)
    
    
    def refreshRedis(cusPhone):
        # 根据顾客电话清楚REDIS缓存
        # cusPhone/客户电话: str  '13701070000'
        try:
            re = redis.Redis(host='121.40.43.10', port=22125, db=0, password='k74FkBwb7252FsbNk2M7')
            cusPhone = 'GatherPhone_' + cusPhone
            re.delete(cusPhone)
            # print('清理REDIS = true')
    
        except Exception as err:
            print('清理REDIS报错: %s' % err)
    
    

    相关文章

      网友评论

          本文标题:python 对数据库基本操作方法

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