Python 数据库操作

#!/usr/bin/env python

-- coding: utf-8 --

import pymysql
import os
import json
import logging
import requests
from flask import Flask, request, jsonify
import pymssql

class Public:

def map(self, description, data):
    if isinstance(data, list):
        dict_data_list = []
        for item in data:
            dict_data = {}
            for i, value in enumerate(description):
                dict_data[value[0]] = item[i]
            dict_data_list.append(dict_data)

        return dict_data_list

def execQuery_json(self, name, sql):
    '''查询数据库,返回json格式'''
    server, database, user, password = Public().getConfig(name)
    if not database:
        raise (NameError, "没有设置数据库信息")
    conn = pymssql.connect(server=server, user=user, password=password, database=database,
                           charset="utf8")
    cur = conn.cursor()
    if not cur:
        raise (NameError, "连接数据库失败")
    else:

        cur.execute(sql)
        result = Public().map(cur.description, list(cur.fetchall()))
        conn.close()
        return result

def execQuery(self, name, sql):
    '''查询数据库'''
    server, database, user, password = Public().getConfig(name)
    if not database:
        raise (NameError, "没有设置数据库信息")
    conn = pymssql.connect(server=server, user=user, password=password, database=database,
                           charset="utf8")
    cur = conn.cursor()
    if not cur:
        raise (NameError, "连接数据库失败")
    else:

        cur.execute(sql)
        resList = cur.fetchall()
        cur.close()
        return resList

def executeSql(self, name, sql):
    '''更新数据库'''
    server, database, user, password = Public().getConfig(name)
    if not database:
        raise (NameError, "没有设置数据库信息")
    conn = pymssql.connect(server=server, user=user, password=password, database=database,
                           charset="utf8")
    cur = conn.cursor()
    if not cur:
        raise (NameError, "连接数据库失败")
    else:
        cur.execute(sql)
        conn.commit()
        cur.close()
def log(self, grade, content):
    '''写log'''
    logging.basicConfig(filename='CCMSMaintain.txt', filemode='+a',
                        format='%(levelname)s -> %(asctime)s: %(message)s', level=logging.DEBUG)

    if grade == 'info':
        logging.info(content)
    elif grade == 'error':
        logging.error(content)

def rest_word(self):
    IP = request.remote_addr
    Public().log('info', '访客id地址: ' + str(IP))
    data = request.data
    Public().log('info', '请求报文: ' + str(data))
    env = request.json.get("env")
    account = request.json.get("account")
    try:
        if env == 'new_sit' or env == 'new_uat':

            for i in account:
                updata_sql = "UPDATE CCMS.dbo.SyEmpInfT SET SeiEmpPwd = cast(0x170D35A546528CA8F22E5C381E55B5AB as varbinary) WHERE seiempnbr = '%s'" % str(
                    i)
                Public().log('info', '执行sql过程: ' + str(updata_sql))
                Public().executeSql(env, updata_sql)

            para = {"status": "success",
                    "code": 1000,
                    "errorMsg": "重置成功",
                    "data": []}
            Public().log('info', '接口返回: ' + str(para))
            return para
        else:
            para = {
                "status": "fail",
                "code": 2000101,
                "errorMsg": "环境信息填写错误,sit请填写:new_sit,uat请填写:new_uat",
                "data": []
            }
            Public().log('error', '异常返回: ' + str(para))
            return para
    except Exception as e:
        Public().log('error', '执行异常原因: ' + str(e))
        para = {"errorMsg": "系统异常请联系管理人员:刘文超 SE0087 手机号码: 18658069531"}
        Public().log('error', '异常返回: ' + str(para))
        return para
上一篇:Sql语言使用备忘录


下一篇:day 44 数据库的安装和环境配置、 库的增删查改、表的增删查改 、 数据的增删查改