首页 > 数据库 >【mysql】关于python建立mysql相关操作

【mysql】关于python建立mysql相关操作

时间:2022-11-19 17:01:03浏览次数:45  
标签:.__ python self mysql write params sql 操作 conn

1.安装

用pip安装指令

pip install pymysql

查看安装成功

#cmd
pip show mysql
#cmd  找list中有该软件
pip list
#python 中不报错
import pymysql

2.操作流程

3.封装代码

#encoding=utf8
#author: blanset

from pymysql import *
import time
class MysqlHelper(object):

    conn_params1 = {'host':'localhost','port':3306,'user':'root','password':'2401','db':'test','charset':'utf8'}
    logfilename = 'log.txt'
    local_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))

    def __init__(self,conn_params):
        self.__host = conn_params['host']
        self.__port = conn_params['port']
        self.__user = conn_params['user']
        self.__password = conn_params['password']
        self.__db = conn_params['db']
        self.__charset = conn_params['charset']

    def __connect(self):
        self.__conn = connect(host=self.__host,port=self.__port,user=self.__user,password=self.__password,db=self.__db,charset=self.__charset)
        self.__cursor = self.__conn.cursor()

    def __close(self):
        self.__cursor.close()
        self.__conn.close()

    def __write_log(self,optype,status,sql):
        with open(self.logfilename,'a') as file:
            s = f'user:{self.__user}|optype:{optype}|opstatus:{status}|optime:{self.local_time}|sql:{sql}'
            file.write(s+'\n')

    def __write_log_p(self,optype,status,sql,params):
        with open(self.logfilename,'a') as file:
            s = f'user:{self.__user}|optype:{optype}|opstatus:{status}|optime:{self.local_time}|sql:{sql}|params:{params}'
            file.write(s+'\n')

    def __write_err_log(self,optype,status,sql,err):
        with open(self.logfilename,'a') as file:
            s = f'user:{self.__user}|optype:{optype}|opstatus:{status}|optime:{self.local_time}|sql:{sql}|err:{err}'
            file.write(s+'\n')

    def __write_err_log_p(self,optype,status,sql,params,err):
        with open(self.logfilename,'a') as file:
            s = f'user:{self.__user}|optype:{optype}|opstatus:{status}|optime:{self.local_time}|sql:{sql}|params:{params}|err:{err}'
            file.write(s+'\n')

    def __edit(self,sql,params,type):
        count = 0
        try:
            self.__connect()
            count = self.__cursor.execute(sql,params)
            self.__conn.commit()
            self.__write_log(type,1,sql)
        except Exception as e:
            print(e)
            self.__conn.rollback()
            self.__write_err_log(type,0,sql,e)
        finally:
            self.__close()
        return count

    def select_one(self,sql,params):
        result = None
        try:
            self.__connect()
            self.__cursor.execute(sql,params)
            result = self.__cursor.fetchone()
            self.__conn.commit()
            self.__write_log('selectone',1,sql)
        except Exception as e:
            print(e)
            self.__conn.rollback()
            self.__write_err_log('selectone',0,sql,e)
        finally:
            self.__close()
        return result

    def select_all(self,sql,params):
        result = ()
        try:
            self.__connect()
            self.__cursor.execute(sql,params)
            result = self.__cursor.fetchall()
            self.__conn.commit()
            self.__writelog('selectall',1,sql)
        except Exception as e:
            print(e)
            self.__conn.rollback()
            self.__write_err_log('selectall',0,sql,e)
        finally:
            self.__close()
        return result

    def insert(self,sql,params):
        return self.__edit(sql,params,'insert')

    def update(self,sql,params):
        return self.__edit(sql,params,'update')

    def delete(self,sql,params):
        return self.__edit(sql,params,'delete')

    def insertmany(self,sql,params):
        count = 0
        try:
            self.__connect()
            count = self.__cursor.executemany(sql,params)
            print(count)
            self.__conn.commit()
            self.__write_log('insertmany',1,sql)
        except Exception as e:
            print('exception:',e)
            self.__conn.rollback()
            self.__write_err_log('insertmany',0,sql,e)
        finally:
            self.__close()
        return count

    def update_many(self,sql,params):
        count = 0
        try:
            self.__connect()
            count = self.__cursor.executemany(sql,params)
            self.__conn.commit()
            self.__write_log('updatemany',1,sql)
        except Exception as e:
            print(e)
            self.__conn.rollback()
            self.__write_err_log('updatemany',0,sql,e)
        finally:
            self.__close()
        return count

    def delete_many(self,sql,params):
        count = 0
        try:
            self.__connect()
            count = self.__cursor.executemany(sql,params)
            self.__conn.commit()
            self.__write_log('deletemany',1,sql)
        except Exception as e:
            print(e)
            self.__conn.rollback()
            self.__write_err_log('deletemany',0,sql,e)
        finally:
            self.__close()
        return count


标签:.__,python,self,mysql,write,params,sql,操作,conn
From: https://www.cnblogs.com/blanset/p/16906449.html

相关文章

  • 深度学习与通信交叉领域的python包:deepcom
    什么是deepcom在进行深度学习与通信领域的交叉研究时,有一些反复使用的算法与训练流程。但是现有的学习框架主要集中在网络的训练部分,对于通信领域的参数压缩与高效传输并......
  • Python学习笔记(三)
    运算符和表达式算术运算python在这里直接支持了幂运算,c的话需要额外的头文件导入此外,python也是支持取模%和取整运算的。The / (division)and // (floordivisi......
  • Mysql 定时删除历史数据
    实现1.创建存储过程3.定时调用这个存储过程创建存储过程(函数)CREATEPROCEDURE`KeepDatasWith30Days`()BEGIN SELECT@maxId:=max(Id)FROMtableNameWHERECreate......
  • [Bug0054] Centos7.x初始化数据库时./mysqld: error while loading shared libraries:
    问题Centos7.x初始化数据库时执行命令行mysqld--initialize--usermysql报错:./mysqld:errorwhileloadingsharedlibraries:libaio.so.1:cannotopensharedobj......
  • Python的线程如何理解
    Num01-->多线程threadingPython中建议使用threading模块,而不要使用thread模块。原因如下:1,Python中threading模块对thread进行了一些包装,可以更加方便的使用。2,Python......
  • 肖sir__面试第六天课程__mysql讲解(8.1)
    数据库一、数据库面试1、你常用过哪些数据库?2、你对sql语句熟悉吗?3、常用sql语句有哪些?4、在工作中你使用数据做什么?5、数据库如何测试?==========================......
  • python3标准库
    本文出处 http://www.cnblogs.com/vamei   作者:Vamei序列(sequence)序列包含有定值表(tuple)和表(list)。字符串(string)是一种特殊的定值表下面的内建函数(buil......
  • 取证初级案例操作大纲
    目录取证初级案例操作大纲1)证据文件中有没有存在被删除的Doc文档?如果有的话,请导出并记录文件名及路径:2)证据文件中有没有存在被删除的图片?如果有的话,请记录文件名及路径......
  • python 协程学习笔记
    yield生成器frominspectimportgetgeneratorstatedefgen1():x=yield2print(x)y=yieldxreturnyg=gen1()print(getgeneratorstate(......
  • python第五章pta习题总结
    四、编程部分1、sorted函数:sorted(iterable,cmp=None,key=None,reverse=False)#iterable:可迭代的对象#cmp:比较规则#key:用来进行比较的对象,只有一个参数2、eval()......