技术笔记
python mysql数据库链接数据库添加数据等操作
 moons   2021-03-17 08:42:16   198
专栏分类: python
import MySQLdb

    def con():
		# 数据库信息
        localhost = 'localhost'
        username = 'root'
        password = 'root'
        dataname = 'douin'
        db = MySQLdb.connect(localhost, username, password, dataname, charset='utf8mb4')
        return db

    # 获取全部数据
	def allData(basename):
        sql = "SELECT * FROM {}".format(basename)
        self.cursor.execute(sql)  # 0没有
        result = self.cursor.fetchall()
        return result
    
	# 添加数据
    def addData(self, data, map, basename):
        # 查询数据库是否存在
        sql = "SELECT * FROM {} WHERE {}".format(basename, map)
        findId = self.cursor.execute(sql)  # 0没有
        if findId:
            # 存在跳过
            print('=> 当前插入用户已存在')
            pass
        else:
            # 插入数据库
            keys = data.keys()
            value = data.values()
            field = ','.join(keys)
            value_item = []
            for item in value:
                item = '"' + str(item).replace('\n', '').replace('\\', '') + '"'
                value_item.append(item)
            values = ','.join(value_item)
            m_sql = 'INSERT INTO {} ({}) values ({})'.format(basename, field, values)
            try:
                self.cursor.execute(m_sql)
            except Exception as e:
                print(e)
            finally:
                self.db.commit()
                print('=> 当前用户插入成功')
				
				
	# 数据插入调用,数据格式为
	info = {
                'aweme_id': item['aweme_id'],
                'uid': item['author_user_id'],
                'content': str(str(item['desc'])).replace('@抖音小助手', ''),
                'share_url': item['share_url'],
                'create_time': item['create_time'],
                'update_time': int(time.time())
            }
            map = "uid = '{}' and a_id = '{}'".format(item['a_id'], item['w_id'])
            self.addData(info, map, 'ms_video')
Copyright © mos360.cn By Moons Soft Studio 百度统计