The future of you, waiting for you in the future.

Geoffrey

Long, long the pathway to Cold Hill;
Drear, drear the waterside so chill.

返回顶部

数据库封装函数

# 数据库/表说明
import pymysql
import redis
from DBUtils.PooledDB import PooledDB
from elasticsearch import Elasticsearch

pool = redis.ConnectionPool(host='xxx.xx.xxx.xxx', port=3306)
redis_con = redis.Redis(connection_pool=pool)
es_con = Elasticsearch([{'host': 'xxx.xx.xxx.xxx', 'port': 9200}])
con_mysql = PooledDB(pymysql, 10, host='xxx.xx.xxx.xxx',
                     port=3306,
                     user='root',
                     passwd='123456',
                     db='xxxx',
                     charset='utf8')


def mysql_func(sql_str, *args):
    """
    :param sql_str: sql语句
    :param args: sql的参数
    :return:
    """
    cursor_connect = con_mysql.connection()
    cursor = cursor_connect.cursor()
    if args:

        cursor.execute(sql_str, args)
    else:
        cursor.execute(sql_str)
    data = cursor.fetchall()
    # 关闭游标和数据库的连接
    cursor.close()
    cursor_connect.commit()
    cursor_connect.close()
    return data


def redis_set_func(key_data, dict_data):
    """
    插入数据到redis
    :param key_data:  哈希的key
    :param dict_data: 字典格式,哈希的字段和值
    :return: 插入后的状态
    """
    # 插入数据到redis
    return_status = redis_con.hmset(key_data, dict_data)
    return return_status


def redis_get_func(hs_key):
    """
    读取redis数据,获取哈希的数据
    :param hs_key: 哈希的key
    :return:
    """
    return_data = redis_con.hgetall(hs_key)

    return return_data


def redis_delete_func(hs_key, *args):
    """

    :param hs_key: 哈希的key
    :param args: 配置参数
    :return: 返回状态
    """
    return_status = redis_con.hdel(hs_key, *args)
    return return_status


if __name__ == '__main__':
    sql_str = "desc order_list"
    print(mysql_func(sql_str))


posted @ 2020-08-19 15:50  Geoffreygau  阅读(188)  评论(0编辑  收藏  举报