Python教程

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

 

这篇关于Python中使用pymsql连接数据库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!