python对数据库操作

复制代码
# -*- coding: utf-8 -*-
"""
@description: xxx
@time: 2019/12/22 1:03
@author: baojinlong
"""

import random
import time
import datetime
import pymysql
from faker import Faker
import pandas as pd


# 从全路径下导入工具类

class MySqlUtils(object):
    # init
    def __init__(self, host, user, password, db_name, port=3306, charset='utf8'):
        self.conn = pymysql.Connect(
            host=host,
            port=port,
            user=user,
            passwd=password,
            db=db_name,
            charset=charset
        )
        self.cursor = self.conn.cursor()

    # insert
    def insert(self, tbName, field, values):
        insSql = 'insert into %s(%s) values (%s)' % (tbName, field, values)
        print('sql=', insSql)
        return self.excute(insSql)

    # select
    def select(self, tbName, field='*', where='1=1'):
        selSql = "select %s from %s where %s" % (field, tbName, where)
        print('sql=', selSql)
        return self.excute(selSql)

    # update
    def update(self, keyValues, tbName, where='1=1'):
        setValue = ''
        for k, v in keyValues.items():
            setValue += '`%s`="%s",' % (k, v)
        if where:
            where = " where " + where
        updateSql = "update %s set %s %s" % (tbName, setValue[:-1], where)
        return self.excute(updateSql)

    # delete
    def delete(self, tbName, where='1=1'):
        delSql = "delete from %s %s where " % (tbName, where)
        return self.excute(delSql)

    # execute
    def excute(self, sql):
        try:
            if sql.find('select') != -1:
                self.cursor.execute(sql)
                return self.cursor.fetchall()
            elif sql.find('insert') != -1 or sql.find('update') != -1 or sql.find('delete') != -1:
                self.cursor.execute(sql)
                self.conn.commit()
                return True
            else:
                return False
        except Exception as e:
            print(str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + '--' + str(e))
            return False

    # __del__
    def __del__(self):
        self.cursor.close()
        self.conn.close()


if __name__ == '__main__':
    # 创建类
    host='xxxxxxxxxxxxx'
    user='xxxxx'
    port=xxxxx
    passwd='xxxxxxx'
    db_name='xxxxxx'
    table_name = 'xxxxx'
    mySqlUtils = MySqlUtils(host, user, passwd, db_name)
    # 读取文件
    all_data = [data for data in open('D:\Data_script\wx_union_id.txt', 'r')]
    print("读取到文件大小", len(all_data))
    for index, value in enumerate(all_data):
        keyValues = {'wx_union_id': value}
        mySqlUtils.update(keyValues, table_name, f'id={index + 1}')
    else:
        print('数据全部更新完毕')
复制代码

 

posted @   tooltime  阅读(348)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
历史上的今天:
2018-05-26 python selenium中Excel数据维护(二)
2018-05-26 python里面的xlrd模块详解(一)
点击右上角即可分享
微信分享提示