
利用python模擬sql語(yǔ)句對(duì)員工表格進(jìn)行增刪改查
本文主要給大家介紹了關(guān)于python模擬sql語(yǔ)句對(duì)員工表格進(jìn)行增刪改查的相關(guān)內(nèi)容,分享出來(lái)供大家參考學(xué)習(xí),下面來(lái)一起看看詳細(xì)的介紹:
具體需求:
員工信息表程序,實(shí)現(xiàn)增刪改查操作:
可進(jìn)行模糊查詢,語(yǔ)法支持下面3種:
select name,age from staff_data where age > 22 多個(gè)查詢參數(shù)name,age 用','分割
select * from staff_data where dept = 人事
select * from staff_data where enroll_date like 2013
查到的信息,打印后,最后面還要顯示查到的條數(shù)
可創(chuàng)建新員工紀(jì)錄,以phone做唯一鍵,phone存在即提示,staff_id需自增,添加多個(gè)記錄record1/record2中間用'/'分割
insert into staff_data values record1/record2
可刪除指定員工信息紀(jì)錄,輸入員工id,即可刪除
delete from staff_data where staff_id>=5andstaff_id<=10
可修改員工信息,語(yǔ)法如下:
update staff_table set dept=Market,phone=13566677787 where dept = 運(yùn)維 多個(gè)set值用','分割
使用re模塊,os模塊,充分使用函數(shù)精簡(jiǎn)代碼,熟練使用str.split()來(lái)解析格式化字符串
由于,sql命令中的幾個(gè)關(guān)鍵字符串有一定規(guī)律,只出現(xiàn)一次,并且有順序!!!
按照key_lis = ['select', 'insert', 'delete', 'update', 'from', 'into', 'set', 'values', 'where', 'limit']的元素順序分割sql.
分割元素作為sql_dic字典的key放進(jìn)字典中.分割后的列表為b,如果len(b)>1,說(shuō)明sql字符串中含有分割元素,同時(shí)b[0]對(duì)應(yīng)上一個(gè)分割元素的值,b[-1]為下一次分割對(duì)象!
這樣不斷迭代直到把sql按出現(xiàn)的所有分割元素分割完畢,但注意這里每次循環(huán)都是先分割后賦值!!!當(dāng)前分割元素比如'select'對(duì)應(yīng)的值,需要等到下一個(gè)分割元素
比如'from'執(zhí)行分割后的列表b,其中b[0]的值才會(huì)賦值給sql_dic['select'],所以最后一個(gè)分割元素的值,不能通過(guò)上述循環(huán)來(lái)完成,必須先處理可能是最后一個(gè)分割元素,再正常循環(huán)!!
在這sql語(yǔ)句中,有可能成為最后一個(gè)分割元素的 'limit' ,'values', 'where', 按優(yōu)先級(jí)別,先處理'limit' ,再處理'values'或 'where'.....
處理完得到sql_dic后,就是你按不同命令執(zhí)行,對(duì)數(shù)據(jù)文件的增刪改查,最后返回處理結(jié)果!!
示例代碼
# _*_coding:utf-8_*_
# Author:Jaye He
import re
import os
def sql_parse(sql, key_lis):
'''
解析sql命令字符串,按照key_lis列表里的元素分割sql得到字典形式的命令sql_dic
:param sql:
:param key_lis:
:return:
'''
sql_list = []
sql_dic = {}
for i in key_lis:
b = [j.strip() for j in sql.split(i)]
if len(b) > 1:
if len(sql.split('limit')) > 1:
sql_dic['limit'] = sql.split('limit')[-1]
if i == 'where' or i == 'values':
sql_dic[i] = b[-1]
if sql_list:
sql_dic[sql_list[-1]] = b[0]
sql_list.append(i)
sql = b[-1]
else:
sql = b[0]
if sql_dic.get('select'):
if not sql_dic.get('from') and not sql_dic.get('where'):
sql_dic['from'] = b[-1]
if sql_dic.get('select'):
sql_dic['select'] = sql_dic.get('select').split(',')
if sql_dic.get('where'):
sql_dic['where'] = where_parse(sql_dic.get('where'))
return sql_dic
def where_parse(where):
'''
格式化where字符串為列表where_list,用'and', 'or', 'not'分割字符串
:param where:
:return:
'''
casual_l = [where]
logic_key = ['and', 'or', 'not']
for j in logic_key:
for i in casual_l:
if i not in logic_key:
if len(i.split(j)) > 1:
ele = i.split(j)
index = casual_l.index(i)
casual_l.pop(index)
casual_l.insert(index, ele[0])
casual_l.insert(index+1, j)
casual_l.insert(index+2, ele[1])
casual_l = [k for k in casual_l if k]
where_list = three_parse(casual_l, logic_key)
return where_list
def three_parse(casual_l, logic_key):
'''
處理臨時(shí)列表casual_l中具體的條件,'staff_id>5'-->['staff_id','>','5']
:param casual_l:
:param logic_key:
:return:
'''
where_list = []
for i in casual_l:
if i not in logic_key:
b = i.split('like')
if len(b) > 1:
b.insert(1, 'like')
where_list.append(b)
else:
key = ['<', '=', '>']
new_lis = []
opt = ''
lis = [j for j in re.split('([=<>])', i) if j]
for k in lis:
if k in key:
opt += k
else:
new_lis.append(k)
new_lis.insert(1, opt)
where_list.append(new_lis)
else:
where_list.append(i)
return where_list
def sql_action(sql_dic, title):
'''
把解析好的sql_dic分發(fā)給相應(yīng)函數(shù)執(zhí)行處理
:param sql_dic:
:param title:
:return:
'''
key = {'select': select,
'insert': insert,
'delete': delete,
'update': update}
res = []
for i in sql_dic:
if i in key:
res = key[i](sql_dic, title)
return res
def select(sql_dic, title):
'''
處理select語(yǔ)句命令
:param sql_dic:
:param title:
:return:
'''
with open('staff_data', 'r', encoding='utf-8') as fh:
filter_res = where_action(fh, sql_dic.get('where'), title)
limit_res = limit_action(filter_res, sql_dic.get('limit'))
search_res = search_action(limit_res, sql_dic.get('select'), title)
return search_res
def insert(sql_dic, title):
'''
處理insert語(yǔ)句命令
:param sql_dic:
:param title:
:return:
'''
with open('staff_data', 'r+', encoding='utf-8') as f:
data = f.readlines()
phone_list = [i.strip().split(',')[4] for i in data]
ins_count = 0
if not data:
new_id = 1
else:
last = data[-1]
last_id = int(last.split(',')[0])
new_id = last_id+1
record = sql_dic.get('values').split('/')
for i in record:
if i.split(',')[3] in phone_list:
print('\033[1;31m%s 手機(jī)號(hào)已存在\033[0m' % i)
else:
new_record = '%s,%s\n' % (str(new_id), i)
f.write(new_record)
new_id += 1
ins_count += 1
f.flush()
return ['insert successful'], [str(ins_count)]
def delete(sql_dic, title):
'''
處理delete語(yǔ)句命令
:param sql_dic:
:param title:
:return:
'''
with open('staff_data', 'r', encoding='utf-8') as r_file,\
open('staff_data_bak', 'w', encoding='utf-8') as w_file:
del_count = 0
for line in r_file:
dic = dict(zip(title.split(','), line.split(',')))
filter_res = logic_action(dic, sql_dic.get('where'))
if not filter_res:
w_file.write(line)
else:
del_count += 1
w_file.flush()
os.remove('staff_data')
os.rename('staff_data_bak', 'staff_data')
return ['delete successful'], [str(del_count)]
def update(sql_dic, title):
'''
處理update語(yǔ)句命令
:param sql_dic:
:param title:
:return:
'''
set_l = sql_dic.get('set').strip().split(',')
set_list = [i.split('=') for i in set_l]
update_count = 0
with open('staff_data', 'r', encoding='utf-8') as r_file,\
open('staff_data_bak', 'w', encoding='utf-8') as w_file:
for line in r_file:
dic = dict(zip(title.split(','), line.strip().split(',')))
filter_res = logic_action(dic, sql_dic.get('where'))
if filter_res:
for i in set_list:
k = i[0]
v = i[-1]
dic[k] = v
line = [dic[i] for i in title.split(',')]
update_count += 1
line = ','.join(line)+'\n'
w_file.write(line)
w_file.flush()
os.remove('staff_data')
os.rename('staff_data_bak', 'staff_data')
return ['update successful'], [str(update_count)]
def where_action(fh, where_list, title):
'''
具體處理where_list里的所有條件
:param fh:
:param where_list:
:param title:
:return:
'''
res = []
if len(where_list) != 0:
for line in fh:
dic = dict(zip(title.split(','), line.strip().split(',')))
if dic['name'] != 'name':
logic_res = logic_action(dic, where_list)
if logic_res:
res.append(line.strip().split(','))
else:
res = [i.split(',') for i in fh.readlines()]
return res
pass
def logic_action(dic, where_list):
'''
判斷數(shù)據(jù)文件中每一條是否符合where_list條件
:param dic:
:param where_list:
:return:
'''
logic = []
for exp in where_list:
if type(exp) is list:
exp_k, opt, exp_v = exp
if exp[1] == '=':
opt = '=='
logical_char = "'%s'%s'%s'" % (dic[exp_k], opt, exp_v)
if opt != 'like':
exp = str(eval(logical_char))
else:
if exp_v in dic[exp_k]:
exp = 'True'
else:
exp = 'False'
logic.append(exp)
res = eval(' '.join(logic))
return res
def limit_action(filter_res, limit_l):
'''
用列表切分處理顯示符合條件的數(shù)量
:param filter_res:
:param limit_l:
:return:
'''
if limit_l:
index = int(limit_l[0])
res = filter_res[:index]
else:
res = filter_res
return res
def search_action(limit_res, select_list, title):
'''
處理需要查詢并顯示的title和相應(yīng)數(shù)據(jù)
:param limit_res:
:param select_list:
:param title:
:return:
'''
res = []
fields_list = title.split(',')
if select_list[0] == '*':
res = limit_res
else:
fields_list = select_list
for data in limit_res:
dic = dict(zip(title.split(','), data))
r_l = []
for i in fields_list:
r_l.append((dic[i].strip()))
res.append(r_l)
return fields_list, res
if __name__ == '__main__':
with open('staff_data', 'r', encoding='utf-8') as f:
title = f.readline().strip()
key_lis = ['select', 'insert', 'delete', 'update', 'from', 'into', 'set', 'values', 'where', 'limit']
while True:
sql = input('請(qǐng)輸入sql命令,退出請(qǐng)輸入exit:').strip()
sql = re.sub(' ', '', sql)
if len(sql) == 0:continue
if sql == 'exit':break
sql_dict = sql_parse(sql, key_lis)
fields_list, fields_data = sql_action(sql_dict, title)
print('\033[1;33m結(jié)果如下:\033[0m')
print('-'.join(fields_list))
for data in fields_data:
print('-'.join(data))
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助
數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼
若不方便掃碼,搜微信號(hào):CDAshujufenxi
SQL Server 中 CONVERT 函數(shù)的日期轉(zhuǎn)換:從基礎(chǔ)用法到實(shí)戰(zhàn)優(yōu)化 在 SQL Server 的數(shù)據(jù)處理中,日期格式轉(zhuǎn)換是高頻需求 —— 無(wú)論 ...
2025-09-18MySQL 大表拆分與關(guān)聯(lián)查詢效率:打破 “拆分必慢” 的認(rèn)知誤區(qū) 在 MySQL 數(shù)據(jù)庫(kù)管理中,“大表” 始終是性能優(yōu)化繞不開的話題。 ...
2025-09-18CDA 數(shù)據(jù)分析師:表結(jié)構(gòu)數(shù)據(jù) “獲取 - 加工 - 使用” 全流程的賦能者 表結(jié)構(gòu)數(shù)據(jù)(如數(shù)據(jù)庫(kù)表、Excel 表、CSV 文件)是企業(yè)數(shù)字 ...
2025-09-18DSGE 模型中的 Et:理性預(yù)期算子的內(nèi)涵、作用與應(yīng)用解析 動(dòng)態(tài)隨機(jī)一般均衡(Dynamic Stochastic General Equilibrium, DSGE)模 ...
2025-09-17Python 提取 TIF 中地名的完整指南 一、先明確:TIF 中的地名有哪兩種存在形式? 在開始提取前,需先判斷 TIF 文件的類型 —— ...
2025-09-17CDA 數(shù)據(jù)分析師:解鎖表結(jié)構(gòu)數(shù)據(jù)特征價(jià)值的專業(yè)核心 表結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 規(guī)范存儲(chǔ)的結(jié)構(gòu)化數(shù)據(jù),如數(shù)據(jù)庫(kù)表、Excel 表、 ...
2025-09-17Excel 導(dǎo)入數(shù)據(jù)含缺失值?詳解 dropna 函數(shù)的功能與實(shí)戰(zhàn)應(yīng)用 在用 Python(如 pandas 庫(kù))處理 Excel 數(shù)據(jù)時(shí),“缺失值” 是高頻 ...
2025-09-16深入解析卡方檢驗(yàn)與 t 檢驗(yàn):差異、適用場(chǎng)景與實(shí)踐應(yīng)用 在數(shù)據(jù)分析與統(tǒng)計(jì)學(xué)領(lǐng)域,假設(shè)檢驗(yàn)是驗(yàn)證研究假設(shè)、判斷數(shù)據(jù)差異是否 “ ...
2025-09-16CDA 數(shù)據(jù)分析師:掌控表格結(jié)構(gòu)數(shù)據(jù)全功能周期的專業(yè)操盤手 表格結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 存儲(chǔ)的結(jié)構(gòu)化數(shù)據(jù),如 Excel 表、數(shù)據(jù) ...
2025-09-16MySQL 執(zhí)行計(jì)劃中 rows 數(shù)量的準(zhǔn)確性解析:原理、影響因素與優(yōu)化 在 MySQL SQL 調(diào)優(yōu)中,EXPLAIN執(zhí)行計(jì)劃是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 對(duì)象的 text 與 content:區(qū)別、場(chǎng)景與實(shí)踐指南 在 Python 進(jìn)行 HTTP 網(wǎng)絡(luò)請(qǐng)求開發(fā)時(shí)(如使用requests ...
2025-09-15CDA 數(shù)據(jù)分析師:激活表格結(jié)構(gòu)數(shù)據(jù)價(jià)值的核心操盤手 表格結(jié)構(gòu)數(shù)據(jù)(如 Excel 表格、數(shù)據(jù)庫(kù)表)是企業(yè)最基礎(chǔ)、最核心的數(shù)據(jù)形態(tài) ...
2025-09-15Python HTTP 請(qǐng)求工具對(duì)比:urllib.request 與 requests 的核心差異與選擇指南 在 Python 處理 HTTP 請(qǐng)求(如接口調(diào)用、數(shù)據(jù)爬取 ...
2025-09-12解決 pd.read_csv 讀取長(zhǎng)浮點(diǎn)數(shù)據(jù)的科學(xué)計(jì)數(shù)法問(wèn)題 為幫助 Python 數(shù)據(jù)從業(yè)者解決pd.read_csv讀取長(zhǎng)浮點(diǎn)數(shù)據(jù)時(shí)的科學(xué)計(jì)數(shù)法問(wèn)題 ...
2025-09-12CDA 數(shù)據(jù)分析師:業(yè)務(wù)數(shù)據(jù)分析步驟的落地者與價(jià)值優(yōu)化者 業(yè)務(wù)數(shù)據(jù)分析是企業(yè)解決日常運(yùn)營(yíng)問(wèn)題、提升執(zhí)行效率的核心手段,其價(jià)值 ...
2025-09-12用 SQL 驗(yàn)證業(yè)務(wù)邏輯:從規(guī)則拆解到數(shù)據(jù)把關(guān)的實(shí)戰(zhàn)指南 在業(yè)務(wù)系統(tǒng)落地過(guò)程中,“業(yè)務(wù)邏輯” 是連接 “需求設(shè)計(jì)” 與 “用戶體驗(yàn) ...
2025-09-11塔吉特百貨孕婦營(yíng)銷案例:數(shù)據(jù)驅(qū)動(dòng)下的精準(zhǔn)零售革命與啟示 在零售行業(yè) “流量紅利見頂” 的當(dāng)下,精準(zhǔn)營(yíng)銷成為企業(yè)突圍的核心方 ...
2025-09-11CDA 數(shù)據(jù)分析師與戰(zhàn)略 / 業(yè)務(wù)數(shù)據(jù)分析:概念辨析與協(xié)同價(jià)值 在數(shù)據(jù)驅(qū)動(dòng)決策的體系中,“戰(zhàn)略數(shù)據(jù)分析”“業(yè)務(wù)數(shù)據(jù)分析” 是企業(yè) ...
2025-09-11Excel 數(shù)據(jù)聚類分析:從操作實(shí)踐到業(yè)務(wù)價(jià)值挖掘 在數(shù)據(jù)分析場(chǎng)景中,聚類分析作為 “無(wú)監(jiān)督分組” 的核心工具,能從雜亂數(shù)據(jù)中挖 ...
2025-09-10統(tǒng)計(jì)模型的核心目的:從數(shù)據(jù)解讀到?jīng)Q策支撐的價(jià)值導(dǎo)向 統(tǒng)計(jì)模型作為數(shù)據(jù)分析的核心工具,并非簡(jiǎn)單的 “公式堆砌”,而是圍繞特定 ...
2025-09-10