封装pymysql
in python with 0 comment

封装pymysql

in python with 0 comment
  1. 数据库配置文件:db/dbConfig.py
db_config={
    'host':'127.0.0.1',
    'port':3306,
    'user':'root',
    'password':'root',
    'database':'epin_copy',
    'charset':'UTF8',
}

#header
  1. 封装文件 db/dbHandle
# coding:utf-8

import pymysql
from db.dbConfig import db_config as df


class dbHandle():
    def __init__(self):
        try:
            self.conn = pymysql.connect(host=df['host'], port=df['port'], user=df['user'], password=df['password'],
                                        database=df['database'], charset=df['charset'])
        except:
            print("连接数据库失败")
        self.cur = self.conn.cursor()

    def dbClose(self):
        if self.conn and self.cur:
            self.cur.close()
            self.conn.close()

    def dbQueryLinks(self,sql):
        link_list = []
        self.cur.execute(sql)
        data = self.cur.fetchall()
        return data
    def dbInsert(self, sql):
        try:
            self.cur.execute(sql)
            print("插入成功!!!")
            self.conn.commit()

        except Exception as e:
            print(e)
            print('插入失败!!!')

    def dbUpdate(self, sql):
        try:
            self.cur.execute(sql)
            print("更新状态成功!!!")
            self.conn.commit()

        except Exception as e:
            print(e)
            print('更新状态失败!!!')
if __name__ == '__main__':
    #测试
    dbHandle = dbHandle()
    data=dbHandle.dbQueryLinks()
Responses