# log 数据库连接
class LogMysql(object):
conn = None
cursor = None def __init__(self):
self.conn = pymysql.connect(host='', user='',
password='',
database='log', charset='utf8')
self.cursor = self.conn.cursor() # 为了方便使用一般会选择将查询结果加上字段名称以字典组的方式返回查询结果
def dict_fetchall(self):
"Return all rows from a cursor as a dict"
# 获取查询字段
columns = [col[0] for col in self.cursor.description]
print(columns)
return [dict(zip(columns, row)) for row in self.cursor.fetchall()] # 获取表列表
def get_table_list(self):
# 判断表是否存在
self.cursor.execute("SHOW TABLES")
res = self.cursor.fetchall()
table_list = []
for i in res:
table_list.append(i[0])
# print("table_list", table_list)
return table_list # redis主库
class Redis(object):
conn = None def __init__(self):
poll = redis.ConnectionPool(host='192.168.5.219', port=6379, db=14, password='root1234@A')
# 本地测试
# poll = redis.ConnectionPool(host='192.168.10.10', port=7000, db=14)
self.conn = redis.Redis(connection_pool=poll)

class LogMysql(object):
    conn = None
    cursor = None
    table = None
    database = None
    def __init__(self, database, table):
        self.table = table
        self.database = database
        self.conn = pymysql.connect(host='rm-2zezqp8sll2swzwby.mysql.rds.aliyuncs.com', user='datacenter',
                                    password='kbs11zx@',
                                    database=self.database, charset='utf8')
        # 本地测试
        # self.conn = pymysql.connect(host='192.168.10.5', user='root',
        #                             password='root',
        #                             database='unionlog', charset='utf8')
        self.cursor = self.conn.cursor()
    # 为了方便使用一般会选择将查询结果加上字段名称以字典组的方式返回查询结果
    def dict_fetchall(self):
        "Return all rows from a cursor as a dict"
        # 获取查询字段
        columns = [col[0] for col in self.cursor.description]
        # print(columns)
        return [dict(zip(columns, row)) for row in self.cursor.fetchall()]
    # 插入数据库
    def insert_db(self, data):
        # ##################### 表名 #####################
        table = self.table
        keys = ', '.join(data.keys())
        values = ', '.join(['%s'] * len(data))
        sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table, keys=keys, values=values)
        try:
            self.cursor.execute(sql, tuple(data.values()))
            print('insert Successful')
            self.conn.commit()
            self.cursor.close()
            self.conn.close()
        except Exception as e:
            print('insert Failed')
            self.conn.rollback()
            self.cursor.close()
            self.conn.close()
    # 更新数据库
    def updata_db(self, data):
        # ##################### 表名 #####################
        table = self.table
        keys = ', '.join(data.keys())
        values = ', '.join(['%s'] * len(data))
        # 实际用的是插入语句,不过加了ON DUPLICATE KEY UPDATE(主键存在,则执行更新操作)
        sql = 'INSERT INTO {table}({keys}) VALUES ({values}) ON DUPLICATE KEY UPDATE'.format(table=table, keys=keys,
                                                                                             values=values)
        update = ','.join([" {key} = %s".format(key=key) for key in data])
        sql += update
        try:
            self.cursor.execute(sql, tuple(data.values()) * 2)
            print('update Successful')
            self.conn.commit()
            self.cursor.close()
            self.conn.close()
        except Exception as e:
            print('update Failed')
            self.cursor.close()
            self.conn.close()
    
    def update_db_sql(self, sql):
        # sql="""update contact set mobile=100088 where name='kate'"""
        try:
            self.cursor.execute(sql)  #执行sql
            self.conn.commit() #提交到数据库
            # db_cursor.execute("select * from contact")
            # ars=db_cursor.fetchall()
            # for rs in ars:
            #     print(rs)
            print('更新成功')
        except Exception as e:
            print("error to update:",e)
            self.conn.rollback()  #发生错误则回滚
            self.cursor.close()
            self.conn.close()

最新文章

  1. Netty入门学习
  2. .NET NLog 详解(一)
  3. 文本对象模型(Document Object Model)
  4. try-catch-finally中return语句的执行
  5. Macbook pro内存升级
  6. 线性表 及Java实现 顺序表、链表、栈、队列
  7. thymeleaf中的th:remove用法
  8. C#常见算法题目(面试准备)
  9. Spark任务调度流程及调度策略分析
  10. RANSAC算法详解
  11. 关于Jaccard相似度在竞品分析中的一点思考
  12. codeforces#410C Mike and gcd problem
  13. 五分钟彻底学会iptables防火墙--技术流ken
  14. go语言中如何模拟100个IP同时并发访问服务器,每个ip要重复访问1000次。每个Ip一分钟之内只能访问一次
  15. js,css文件更新之后,浏览器端还有缓存,久久不能消除
  16. ionic的学习-01搭建App的起步准备
  17. Android之JSON格式数据解析
  18. oracle 删除重复数据
  19. sqlserver2014新特性
  20. mysql资源总结

热门文章

  1. 所谓 ICMP,不过将军与士卒而已
  2. math random模块
  3. 博客之初体验-----python初了解
  4. pc/shouji/weixin判断跳转
  5. POJ2406 KMP前缀周期
  6. RESTful中的PUT和PATCH实践
  7. TP之安全机制
  8. PHP基础-数组
  9. 详解Tomcat核心配置、http协议
  10. Java 并发编程(一) → LockSupport 详解