Python简单实现mysql工具类

import pymysql
import configparser

# 打开连接
def create_connect():
    conn = pymysql.connect(host='localhost', user='root', password='123456', database='largescreen')
    cur = conn.cursor(cursor=pymysql.cursors.DictCursor)  # commond对象

    return conn,cur


# 关闭连接
def close_connect(conn,cur):
    cur.close()
    conn.close()

# 执行查询操作
def loadDataBySql(sql):
    try:
        conn,cur = create_connect()

        cur.execute(sql)

        list = cur.fetchall()
        close_connect(conn,cur)

        return list
    except:
        return 'error'

# 执行非查询操作
def excuteBySql(sql):
    ir = 0
    conn, cur = create_connect()

    try:
        ir = cur.execute(sql)
        if ir > 0:
            conn.commit()
        else:
            conn.rollback()
    except:
        ir = -100
        conn.rollback()

    close_connect(conn,cur)

    return ir

# 以事务方式执行多条sql
def excutemany_sql(sql, datalist):
    ir = 0
    conn, cur = create_connect()

    try:
        ir = cur.executemany(sql, datalist)
        if ir > 0 :
            conn.commit()
        else:
            conn.rollback()
    except:
        ir = -100
        conn.rollback()

    close_connect(conn, cur)

    return ir


你可能感兴趣的:(python,mysql,开发语言)