python操作mysql数据库

# 数据库操作
import pymysql

class mysqlHelper(object):

    def __init__(self, host, user, pw, db):
        """连接数据库,创建游标"""
        # self.conn = pymysql.connect(host='localhost', user='root', password='111212', database='students')
        self.host, self.user, self.pw, self.db = host, user, pw, db

        # 定制游标 拿出数据成字典
        # self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    def __GetConnect(self):
        if not self.db:
            raise (NameError, "没有数据库信息")

        self.conn = pymysql.connect(host=self.host, user=self.user, password=self.pw, database=self.db)
        cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)# 定制游标 拿出数据成字典 默认元组方式拿出数据
        if not cursor:
            raise (NameError, "数据库连接失败")
        else:
            return cursor

    def ExecQueryALL(self, sql, args=()): # sql即SQL语句,args为SQL所需参数
        cursor = self.__GetConnect()
        result = cursor.execute(sql, args)
        gdata = cursor.fetchall() # 获取所有符合sql select语句的值
        cursor.close() # 关闭游标
        self.conn.close() # 关闭连接
        return [result, gdata]

    def ExecQueryOne(self, sql, args=()):
        cursor = self.__GetConnect()
        result = cursor.execute(sql, args)
        gdata = cursor.fetchone() # 获取一个符合sql select语句的值
        cursor.close()
        self.conn.close()
        return [result, gdata]

    def ExecNonQueryMany(self, sql, args=()):
        cursor = self.__GetConnect()
        result = cursor.executemany(sql, args)
        self.conn.commit() # update、delete、insert into 多条提交
        lastmod = cursor.lastrowid # 获取最新插入数据的自增值
        cursor.close()
        self.conn.close()
        return [result, lastmod]

    def ExecNonQueryOne(self, sql, args=()):
        cursor = self.__GetConnect()
        result = cursor.execute(sql, args)
        self.conn.commit() # update、delete、insert into 单挑提交
        lastrowid = cursor.lastrowid # 获取最新插入数据的自增值
        cursor.close()
        self.conn.close()
        return [result, lastrowid]

调用:

mysqlop = mysqlHelper("localhost","root","111212","students")
getplanName = mysqlop.ExecQueryOne(sql='select planName from taskplan where planName=%s limit 1',args=(tasklist[0]['planName']))
print(getplanName)

 

你可能感兴趣的:(python,mysql,python,pymysql,封装)