码迷,mamicode.com
首页 > 数据库 > 详细

pymysql DAO简单封装

时间:2019-10-15 12:59:00      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:turn   color   int   char   getc   def   数据   except   data   

 

 

#!/usr/bin/env python
# -*-coding:utf-8 -*-
#
#  无法执行多个query,self.conn.close()放在CdbConn类的单独函数中,每次query之后要手动close;否则多次query,会自动关闭
import pymysql


class CdbConn():
    def __init__(self, db_host,  db_user, db_pwd, db_name, db_port=3306):
        self.db_host = db_host
        self.db_port = db_port
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.db_name = db_name
        self.status = True
        self.conn = self.getConnection()


    def getConnection(self):
        try:
            conn =  pymysql.Connect(
                host=self.db_host,  # 设置MYSQL地址
                port=int(self.db_port),  # 设置端口号
                user=self.db_user,  # 设置用户名
                passwd=self.db_pwd,  # 设置密码
                db=self.db_name,  # 数据库名
                charset=utf8,  # 设置编码
                use_unicode=True
            )
            return conn
        except Exception as e:
            self.status = False
            print(数据库连接异常: , e)

    def query(self, sqlString):
        cursor = self.conn.cursor()
        cursor.execute(sqlString)
        returnData = cursor.fetchall()
        cursor.close()
        # self.conn.close()
        return returnData

    def close(self):
        self.conn.close()

    def update(self, sqlString):
        cursor = self.conn.cursor()
        cursor.execute(sqlString)
        self.conn.commit()
        cursor.close()
        # self.conn.close()

 

pymysql DAO简单封装

标签:turn   color   int   char   getc   def   数据   except   data   

原文地址:https://www.cnblogs.com/yum777/p/11676806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!