pymysql运行自定义语句

import pymysql

pymysql.install_as_MySQLdb()

host = '127.0.0.1'
user = 'user '
password = 'password '
port = 3306
database = 'database'

conn_database = {
    'host':host,
    'user':user,
    'password':password,
    'port':port,
    'database':database
}




def select_datas(sql):
    with pymysql.connect(**conn_database) as connection:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            columns = [col[0] for col in cursor.description]
            datas = [dict(zip(columns, row)) for row in cursor.fetchall()]
        return datas


def insert_datas(sql):
    with pymysql.connect(**conn_database) as connection:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            issucc = cursor.rowcount
            if issucc > 0:
                return True
            else:
                return False


def update_datas(sql):
    with pymysql.connect(**conn_database) as connection:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            issucc = cursor.rowcount
            if issucc > 0:
                return True
            else:
                return False



def delete_datas(sql):
    with pymysql.connect(**conn_database) as connection:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            issucc = cursor.rowcount
            if issucc > 0:
                return True
            else:
                return False

 


如需要添加自动提交
autocommit = True

 

posted @ 2022-06-29 10:45  CodeYaSuo  阅读(67)  评论(0编辑  收藏  举报