sql的简单实现增删改查

用到正则,函数,排序等基础知识,可以用来练练手

import re

tableName = 'staff_table'


# 1.可进行模糊查询,语法至少支持下面3种查询语法:
# 2.可创建新员工纪录,以phone做唯一键(即不允许表里有手机号重复的情况),staff_id需自增
# 3.可删除指定员工信息纪录,输入员工id,即可删除
# 4.可修改员工信息,语法如下:
# find name,age from staff_table where age > 22
# find * from staff_table where dept = "IT"
# find * from staff_table where enroll_date like "2013"
# 语法: add staff_table Alex Li,25,134435344,IT,2015‐10‐29
# 语法: del from staff_table where staff_id=3
# UPDATE staff_table SET dept="Market" WHERE dept = "IT" 把所有dept=IT的纪录的dept改成Market
# UPDATE staff_table SET age=25 WHERE name = "Alex Li" 把name=Alex Li的纪录的年龄改成25

def fuzzyQuery(sql):
    print('begin query')
    r = re.search('find\s*(.*)\s*from\s*(.*)\swhere\s*(.*)', sql)
    conditions = r.groups()
    if not conditions or len(conditions) != 3:
        print('Sql error')
    if conditions[1] != tableName:
        print('Table name error')
    findColumns = conditions[0]
    whereSql = conditions[2]
    ids = getIdByWhere(whereSql)
    print('查询出了%s条' % (len(ids),))
    print('result:')
    for id in ids:
        if findColumns.strip() == '*':
            print(idDetailMap.get(id))
        else:
            printResult = ''
            findColumnsList = findColumns.split(',')
            for column in findColumnsList:
                columnIndex = columnIndexMap.get(column.strip())
                if not columnIndex:
                    raise Exception('find columns error')
                else:
                    printResult += str(idDetailMap.get(id)[columnIndex])
            print(printResult)


def addInfo(sql):
    print('begin add')
    r = re.search('add\s*%s\s*(.*)' % (tableName,), sql)
    addInfo = r.groups()
    if addInfo:
        addInfoList = addInfo[0].split(',')
        if len(addInfoList) != len(columnIndexMap) - 1:
            raise ('add info error')
        phone = addInfoList[columnIndexMap.get('phone') - 1]
        existsPhones = [info[columnIndexMap.get('phone')] for info in infoList]
        if phone in existsPhones:
            raise Exception('电话不可重复')
        maxId = max([int(info[columnIndexMap.get('staff_id')]) for info in infoList]) if infoList else 0
        newId = maxId + 1
        f.write('\n' + str(newId) + ',' + addInfo[0])
        f.flush()
        print('新增一条信息')
        # 修改文件后更新相关数据
        getEmployeeInfo()


def delInfo(sql):
    print('begin del')
    r = re.search('del\s*from\s*%s\s*where\s*(.*)' % (tableName,), sql)
    ids = getIdByWhere(r.groups()[0])
    for id in ids:
        del idDetailMap[id]
    updateFile()
    print('删除了%s条数据'%(len(ids),))


def updateFile():
    f.seek(0)
    f.truncate()
    sortedIdDetailMap = sorted(idDetailMap.items(), key=lambda x: int(x[0]))
    for k in sortedIdDetailMap:
        row = ",".join(k[1])
        f.write("%s\n" % row)
    f.flush()
    getEmployeeInfo()


def updateInfo(sql):
    print('begin update')
    r = re.search('update\s*%s\sset\s*(.*)\s*where\s*(.*)' % (tableName,), sql).groups()
    ids = getIdByWhere(r[1])
    updateColumn = r[0].split('=')[0].strip()
    if updateColumn == 'staff_id':
        raise Exception('staff_id 不能被修改')
    updateColumnValue = str(eval(r[0].split('=')[1].strip()))
    for id in ids:
        idDetailMap[id][columnIndexMap.get(updateColumn)] = updateColumnValue
    updateFile()
    print('更新了%s条数据' % (len(ids)))


def getIdByWhere(whereSql):
    '''
    目前只考虑一个条件
    :param whereSql:
    :return:
    '''
    r = re.search('(\S*)\s*(=|<=|>=|<|>|like)\s*(.*)', whereSql)
    group = r.groups()
    if not group or len(group) < 3:
        raise Exception('where sql error')
    column = group[0]
    columeIndex = columnIndexMap.get(column)
    if columeIndex is None:
        raise Exception(column, 'not exists')
    value = group[2]

    if group[1] == 'like':
        operation = ' in '
        columeValues = [i[0] for i in infoList if eval('%s%s%s' % (
            value, operation,
            i[columeIndex] if i[columeIndex].isdigit() else '"' + i[columeIndex].lower() + '"'))]

    else:
        operation = ' == ' if group[1] == '=' else group[1]
        columeValues = [i[0] for i in infoList if eval('%s%s%s' % (
            i[columeIndex] if i[columeIndex].isdigit() else '"' + i[columeIndex].lower() + '"', operation, value))]

    print('found staff_id: %s' % (str(columeValues),))
    return columeValues


# 获取员工信息
def getEmployeeInfo():
    global infoList, f, idDetailMap
    f.seek(0)
    rawData = f.readlines()
    infoList = []
    idDetailMap = {}
    for item in rawData:
        rowData = item.rstrip('\n').split(',')
        if rowData:
            infoList.append(rowData)
        idDetailMap[rowData[columnIndexMap.get('staff_id')]] = rowData
    print(infoList)
    return infoList, idDetailMap


infoFile = "employeeInfo.txt"
f = open(infoFile, 'r+', encoding='utf-8')
columnIndexMap = {"staff_id": 0, "name": 1, "age": 2, "phone": 3, "dept": 4, "enroll_date": 5}
infoList, idDetailMap = getEmployeeInfo()

try:
    while True:
        try:
            sql = input('sql:')
            sql = sql.strip().lower()
            if sql.startswith('find'):
                fuzzyQuery(sql)
            elif sql.startswith('add'):
                addInfo(sql)
            elif sql.startswith('del'):
                delInfo(sql)
            elif sql.startswith('update'):
                updateInfo(sql)
            elif sql == 'quit':
                print('quit')
                f.close()
                break
            else:
                print('sql invalid')
                continue
        except Exception as e:
            print('error msg:', e.__str__())
finally:
    if f:
        f.close()

employeeInfo.txt

1,Alex Li,22,13651054608,IT,2013‐04‐01
2,Jack Wang,28,13451024608,HR,2015‐01‐07
4,Mack Qiao,44,15653354208,Sales,2016‐02‐01
5,Rachel Chen,23,13351024606,IT,2013‐03‐16
6,Eric Liu,19,18531054602,Marketing,2012‐12‐01
7,Chao Zhang,21,13235324334,Administration,2011‐08‐08
8,Kevin Chen,22,13151054603,Sales,2013‐04‐01
9,Shit Wen,20,13351024602,IT,2017‐07‐03
10,Shanshan Du,26,13698424612,Operation,2017‐07‐02

你可能感兴趣的:(sql的简单实现增删改查)