Python中使用pymsql连接数据库

Python中使用pymsql连接数据库
from app import app
import pymysql
import config


class Database:
    aurl = config.aurl
    user = config.user
    password =config.password
    db = config.db
    charset = config.charset

    def __init__(self):
        self.connection = pymysql.connect(host=self.aurl, user=self.user, password=self.password, database=self.db, charset=self.charset)
        self.cursor = self.connection.cursor()

#插入
    def insert(self, query, params):
        inset_id=0
        try:
            self.cursor.execute(query, params)
            inset_id=self.connection.insert_id()  #返回插入行的id
            self.connection.commit()
            return inset_id
        except Exception as e:
            # 若有异常就回滚;
            self.connection.rollback()
            app.logger.info("Error: insert to fecth data", e)
            return inset_id
        finally:
            self.connection.close()  # 关闭连接

#查询
    def query(self, query, params):
        try:
            self.cursor.execute(query, params)
            return self.cursor.fetchall()
        except Exception as e:
            print("Error: unable to fecth data")
            app.logger.info("Error: query to fecth data",e)
        finally:
            self.connection.close()  # 关闭连接


#查询一个
    def queryone(self, query, params):
        try:
            self.cursor.execute(query, params)
            return self.cursor.fetchall()
        except Exception as e:
            print("Error: unable to fecth data")
            app.logger.info("Error: queryone to fecth data",e)
        finally:
            self.connection.close()  # 关闭连接

#更新
    def update(self,sql,params):
        row=0
        try:
            row=self.cursor.execute(sql, params)
            self.connection.commit()
            return row
        except Exception as e:
            # 若有异常就回滚;
            self.connection.rollback()
            app.logger.info("Error: update to fecth data", e)
            return row
        finally:
            self.connection.close()  # 关闭连接

# 删除
    def delete(self,sql,params):
        row=0
        try:
            row=self.cursor.execute(sql, params)
            self.connection.commit()
            return str(row)
        except Exception as e:
            # 若有异常就回滚;
            self.connection.rollback()
            app.logger.info("Error: delete to fecth data", e)
            return row
        finally:
            self.connection.close()  # 关闭连接

    # def __del__(self):
    #     self.connection.close()

if __name__ == '__main__':
    pass
View Code

 

上一篇:环形图+牵引线+划上显示边框其余淡出


下一篇:http接口上传下载文件(RestTemplate)