zoukankan      html  css  js  c++  java
  • 随笔:Python连接数据库、插入数据方法封装

    随笔:Python连接数据库方法封装

    from MySQLdb import *
    # 连接数据库
    class Connect_database(object):
        # 连接数据库
        def __init__(self, host, port, user, password, db, charset='utf8'):
            self.host = host
            self.port = port  # mysql端口
            self.username = user  # mysql远程连接用户名
            self.password = password  # mysql远程连接密码
            self.db = db  # mysql使用的数据库名
            self.charset = charset  # mysql使用的字符编码,默认为utf8
            try:
                self.connect_database = connect(host=self.host, port=self.port, user=self.username, password=self.password, db=self.db, charset=self.charset)
            except:
                print('连接失败')
                
        # 插入数据
        def insert_data(self, batch, name, call_time, status, tablename='table', time_run=None, err_log=None):
            sql = "insert into " + tablename + "(model, call_time, status, time_run, err_log, batch) values('%s', '%s', '%s', '%s', '%s', %d)" 
                  % (name, call_time, status, time_run, err_log, batch)
            try:
                cur = self.connect_database.cursor()
                cur.execute(sql)
                self.connect_database.commit()
                cur.close()
                result = sql+'插入成功'
            except Exception as e:
                print('插入失败', e)
                result = sql+'插入失败'
                self.connect_database.rollback()
            return result
    
        def close_database(self):
            self.connect_database.close()
    
    
  • 相关阅读:
    jQuery事件
    jQuery选择器
    jQuery对象和语法
    jQuery简介
    残差的正态性检验——概率图和QQ-plot图
    https://oldpan.me/深度学习博客
    深度学习的内存消耗在哪里?
    图片缩放
    随机梯度下降批尺寸的影响
    利用PIL.ImageOps.invert实现二值图像黑白反转
  • 原文地址:https://www.cnblogs.com/caodingzheng/p/14007078.html
Copyright © 2011-2022 走看看