【python】Mysql访问类

#coding:utf-8
import configparser
import pymysql
import os

class MysqlHelper(object):
    def __init__(self):
        config_path=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        CONFIGFILE=config_path+'/config.ini'
        print(CONFIGFILE)
        cf=configparser.RawConfigParser()
        cf.read(CONFIGFILE)
        DBHOST=cf.get('db','dbhost')
        DBNAME=cf.get('db','dbname')
        DBUSER=cf.get('db','dbuser')
        DBPWD=cf.get('db','dbpwd')
        DBCHARSET=cf.get('db','dbcharset')
        DBPORT=cf.get('db','dbport')
        self._dbhost=DBHOST
        self._dbname=DBNAME
        self._dbuser=DBUSER
        self._dbpwd=DBPWD
        self._dbcharset=DBCHARSET
        self._dbport=int(DBPORT)
    #创建数据库连接
    def ConnectMysql(self):
        self._conn=False
        self._conn=pymysql.connect(self._dbhost,self._dbuser,self._dbpwd,self._dbname,self._dbport)
        if self._conn:
            self._cursor=self._conn.cursor()

    #关闭数据库连接
    def CloseMysql(self):
        if self._conn and self._cursor:
            self._cursor.close()
            self._conn.close()

    #执行sql语句,增删改
    def ExecuteSql(self,sql,params=None):
        self.ConnectMysql()
        try:
            if self._conn and self._cursor:
                rowcount=self._cursor.execute(sql,params)
                self._conn.commit()
                self.CloseMysql()
        except:
            print("数据库操作失败!")
            self._conn.rollback()
            return False
        return rowcount

    #查询所有的数据
    def FetchAll(self,sql,params=None):
        self.ConnectMysql()
        try:
            if self._conn and self._cursor:
                self._cursor.execute(sql,params)
                results=self._cursor.fetchall()
                self.CloseMysql()
        except:
            print("查询失败!")  
            return False
        return results

#config.ini
[db]
dbhost:服务器
dbname:数据库
dbuser:用户名
dbpwd:密码
dbcharset:utf-8
dbport:3306

你可能感兴趣的:(【python】Mysql访问类)