封装pymysql

Posted zengsf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了封装pymysql相关的知识,希望对你有一定的参考价值。

from pymysql import connect

class MysqlHelp:
    def __init__(self,database,host = "localhost", user = "zengsf", 
            password = "密码", charset = "utf8", port = 3306):
        self.database = database
        self.host = host
        self.user = user
        self.password = password
        self.charset = charset
        self.port = port

    #创建对象
    def open(self):
        #创建conn
        self.conn = connect(host = self.host, user = self.user,
                            password = self.password, database = self.database,
                            charset = self.charset, port = self.port)
        #创建游标
        self.cur = self.conn.cursor()

    #关闭
    def close(self):
        self.cur.close()
        self.conn.close()

    #执行SQL语句
    def workOn(self, sql, L=[]):
        self.open()
        try:
            self.cur.execute(sql, L)
            self.conn.commit()
        except Exception as e:
            self.conn.rollback()
        self.close()

    #getAll查询方法
    def getAll(self, sql, L=[]):
        self.open()
        self.cur.execute(sql, L)
        result = self.cur.fetchall()
        self.close()
        return result

if __name__ == "__main__":
    #测试 
    mysql = MysqlHelp("shengfen")
#    sql_insert = "insert into sheng(s_name) values(‘美国‘);"
#    mysql.workOn(sql_insert)
    sql_select = "select * from sheng;"
    result = mysql.getAll(sql_select)    
    print(result)

 

以上是关于封装pymysql的主要内容,如果未能解决你的问题,请参考以下文章

数据库操作 pymysql 封装处理(中级)

DBUtils 和 pymysql 结合的简单封装

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

pymysql封装