上回书说到,这两天突然闲着没事,想自己做一个数据库。
上次是已经把登录系统做完了(见代码):
import json#json解析 import os#数据读写,文件操作 import sys#控制退出 import time#控制暂停 import shutil#文件夹操作 def saveToJSON(dicObject,file): flag=False '''#这一段注释掉了,因为后面发现这样不能完全满足使用需求。 if type(dicObject)!=dict: print('dict') return flag ''' try: j_file=open("./PyDB/"+file,'a')#打开文件,PyDB是储存数据的文件夹,后面会说到 json.dump(dicObject,j_file,ensure_ascii=False)#以JSON格式储存数据 flag=True except: print('写数据出错!') finally: if flag: j_file.close() return flag #========================= def GetFromJSON(filename): flag=False dicObject={} try: way="./PyDB/"+filename#文件路径 j_file=open(way,'r')#以只读方式打开文件 dicObject=json.load(j_file)#使用json的load方法解析数据 flag=True except: flag=False finally: if flag: j_file.close() elif flag==False: return False return dicObject def turn(file): with open(file,mode='r',encoding='utf-8') as f:#用with语句打开文件 a=f.readline()#将文件以字符串形式读出 a=a.split('","')#以“,”为间隔,将字符串分割成表格 b=[]#返回的列表 for i in range(len(a)): if i <= len(a)-2:#a的结尾会有一个‘“,”’,需要把它去掉 b.append(json.loads(a[i]))#用json解析字符串并添加到列表中 return b if __name__ == '__main__': print("| Welcome to PyDB Monitor.")#一些简要信息 print("| Server version: 1.0.0 PyDB Server.") print("| Add '@' at the beginning of the statement.") print("| Type '@help' or '@h' for help.Type '@continue' or '@c' to clear the current input statement.\n") print("PyDB>Welcome to PyDB!"+"\n")#欢迎语句 folder=''#判断是否存在数据库文件夹 for i in range(len(os.listdir())): a=os.listdir() if a[i]=='PyDB': folder='PyDB' if folder!='PyDB':#如果没有,则创建数据库文件夹 os.makedirs('./PyDB'+'./user') os.makedirs('./PyDB'+'./DataBase') #----------------------------------------------------登录 while True: if len(os.listdir('./PyDB/user'))==0:#判断是否存在用户,如果没有,则创建一个超级管理员 print("PyDB> There are no users yet :( ... Let's create one! :) \n") admin=input("PyDB> Please enter your User Name!\nAdministrator>") Pass=input("PyDB> Please enter your password!\nPassword>") RePass=input("PyDB> Please enter your password again!\nPassword>") if Pass==RePass:#判断两次输入的密码是否一致 #用户信息 info={ 'Name':admin,'Password':Pass,'Jurisdiction':'Root' } saveToJSON(info,'user/'+admin+'.json')#储存信息 print("\nSuccess>Congratulations, account creation succeeded!\n") host=GetFromJSON("user/"+admin+".json")#为后面的一些判断做准备 os.makedirs('./PyDB'+'./DataBase'+'./'+admin)#在数据库文件夹下创建用户文件夹 break#跳出循环,进行数据操作 else:#不一致则进入另一个循环 while True: print('PyDB>The two passwords you entered are different. Please try again.') Pass=input("PyDB> Please enter your password!\nPassword>") RePass=input("PyDB> Please enter your password again!\nPassword>") if Pass==RePass: info={ 'User':admin,'Password':Pass,'Jurisdiction':'Root' } saveToJSON(info,'user/'+admin+'.json') print("\nSuccess>Congratulations, account creation succeeded!\n") host=GetFromJSON("user/"+admin+".json") os.makedirs('./PyDB'+'./DataBase'+'./'+admin) break break else:#如果存在用户,则进行登录操作 while True: admin=input('User name>') if admin=="@exit":#若需退出,则可以在此退出 print("PyDB>Thank you for your use~ :) Bye!") time.sleep(3) sys.exit() if GetFromJSON("user/"+admin+".json")==False:#判断该用户是否存在 print("Error>Sorry, there is no such user.Please try again.") else: host=GetFromJSON("user/"+admin+".json")#获取用户信息 break Pass=input('Password>')#用户密码 if Pass=="@exit":#若需退出,则可以在此退出 print("PyDB>Thank you for your use~ :) Bye!") time.sleep(3) sys.exit() if host["Password"]!=Pass:#若三次密码错误,则退出程序 print("Error>Password error, please try again!") Pass=input('Password>') host=GetFromJSON("user/"+admin+".json") if host["Password"]!=Pass: print("Error>Password error, please try again!") Pass=input('Password>') host=GetFromJSON("user/"+admin+".json") if host['Password']!=Pass: print("Error>You have made three consecutive errors. Please try again later.") time.sleep(3) sys.exit() else: print("\n"+"PyDB>Welcome,"+admin+'!\n') break else: print("\n"+"PyDB>Welcome,"+admin+'!\n') break else: print("\n"+"PyDB>Welcome,"+admin+'!\n') break#进入操作界面
那么今天,我们来做后面的数据操作系统!(即第二个大循环)
jurisdiction=host["Jurisdiction"] maindatabase=''
这个“jurisdiction"就是用户的权限,这个在后面我们会用到(毕竟谁也不想让别人随便创建用户和修改自己的数据)。而”maindataabase"则是使用的数据库,默认为没有选择,需要用户自行选择。
while True: user_e=input('PyDB>') User_database_path="PyDB/DataBase/"+admin
这边的user_e就是用户输入的语句,“User_database_path”则是用户的数据库路径。
#----------------------------------------------帮助列表 if user_e=='@h' or user_e=='@help': DBhelp()
这个帮助函数(DBhelp)是这样子的,要放在循环前,不然会报错:
def DBhelp(): print("Command list:") print("|Command |Explain |") print("-----------------------------------------------------------------------") print("|@choose |Choose a database to use. |") print("|@create table |Generate a table under the current database. |") if host["Jurisdiction"]=="Root": print("|@create user |Create a new user. |") print("|@c or @continue |Clear the current input statement. |") print("|@create database |Create a database according to the boot. |") print("|@del table |Delete a table. |") print("|@del database |Delete a database. |") print("|@exit |Exit the program. |") print("|@h or @help |Get the command list. |") print("|@insert |Insert data into a table. |") print("|@show users |View all users. |") print("|@show tables |View tables under the current database. |") print("|@show database |View the database under the current user. |") print("|@query data |Query data in the selected table. |") print()
就是一个命令列表,因为还在更新,所以不是很全。
主要的命令列表是这样的:
Command(命令) | Explain(解释) |
@choose | Choose a database to use.(选择一个需要使用的数据库) |
@create table | Generate a table under the current database.(在当前数据库下创建一个表格) |
@create user | Create a new user.(创建一个新用户) |
@c or @continue | Clear the current input statement.(清除当前输入的语句) |
@createdatabase | Create a database according to the boot.(根据引导创建数据库) |
@del table | Delete a table.(删除一个表格) |
@del database | Delete a database.(删除一个数据库) |
@exit | Exit the program.(退出程序) |
@h or @help | Get the command list.(获得指令列表) |
@insert | Insert data into a table.(把数据插入到表格中) |
@show users | View all users.(查看所有的用户) |
@show tables | View tables under the current database.(查看当前数据库下的所有表格) |
@show database | iew the database under the current user.(查看当前用户下的所有数据库) |
@query data | Query data in the selected table. |
以上是这个数据库的指令列表(还在更新),所有的操作只需要根据引导去做即可。
所有指令对应的操作都在后面(不是按表格顺序来):
清除当前输入的语句:
if user_e=='@c' or user_e=='@continue': continue
很简单,直接跳过就好了。
退出程序:
elif user_e=='@exit': print("PyDB>Thank you for your use~ :) Bye!") time.sleep(3) sys.exit()
打印一个告别语,等待三秒,退出~~
选择数据库:
elif user_e=='@choose': maindatabase=input('Select>') find=os.listdir(User_database_path) yesorno=False for i in find: if i==maindatabase: yesorno=True if yesorno==False: print("Error>This database does not exist.\n") else: print('PyDB>Database changed.\n')
先获取输入的数据库,然后用os的lisetdir方法在当前用户文件夹下循环查找,如不存在则报错,若存在则说明“数据库改变了”,同时改变“maindatabae”。
展示数据库:
elif user_e=="@show database": database_num=os.listdir(User_database_path) databases='' if database_num==[]: print("PyDB>There is no database yet. Use '@create database' to create one!\n") else: for i in range(len(database_num)): if i<len(database_num)-1: databases+=database_num[i]+',' else: databases+=database_num[i] print(" | "+databases+' |')
用os库的listdir方法获取用户目录下的文件夹(数据库)并打印,若没有则提示创建一个。
创建数据库:
elif user_e=="@create database": database_num=os.listdir(User_database_path) basename=input("PyDB>Please enter the Name of the Database.\nCreate>") os.makedirs('./PyDB'+'./DataBase'+'./'+admin+'./'+basename) print("Success>Database creation succeeded!\n")
同样用os的lisetdir方法判断该数据库是否存在,如不存在则创建并打印提示信息。
创建表格:
elif user_e=="@create table": if maindatabase=='': print("PyDB>Please choose a database first!\n") else: tablename=input('PyDB>Please enter the name of the table.\nCreate>') database_path=os.listdir('PyDB/Database/'+admin+'/'+maindatabase) yesorno=False for i in database_path: i=i.replace(".json",'') if i==tablename: yesorno=True if yesorno==True: print("Error>This table already exists.\n") else: columns=input("PyDB>Please enter the title of each column.\nCreate>") columns=columns.split(',') column_dict={} for i in range(len(columns)): column_dict.setdefault(str(i+1),columns[i]) saveToJSON(column_dict,'Database/'+admin+'/'+maindatabase+'/'+tablename+'.json') saveToJSON(',','Database/'+admin+'/'+maindatabase+'/'+tablename+'.json') print("Success>Successfully created the table!\n")
展示表格:
elif user_e=="@show tables": if maindatabase=='': print("PyDB>Please choose a database first!\n") else: database_path=os.listdir('PyDB/Database/'+admin+'/'+maindatabase) if database_path==[]: print("PyDB>There is no table yet. Use '@create table' to create one!\n") else: show_tables='' for i in range(len(database_path)): toshow=database_path[i] if i<len(database_path)-1: show_tables+=toshow.replace('.json','')+',' else: show_tables+=toshow.replace('.json','') print(' |'+show_tables+' |\n')
首先,查看有没有选择数据库,其他的和上面的展示数据库差不多,这里就不过多赘述了。
删除数据库:
elif user_e=="@del database": del_base=input("PyDB>Please enter the name of the database to delete.\nDelete>") database_path=os.listdir('PyDB/Database/'+admin) yesorno=False for i in database_path: if i==del_base: yesorno=True if yesorno==False: print("Error>This database doesn't exists.\n") else: database_path=os.listdir('PyDB/Database/'+admin+'/'+del_base) if database_path==[]: if maindatabase==del_base: maindatabase='' os.rmdir('PyDB/Database/'+admin+'/'+del_base) print("Success> Successfully deleted this database!\n") else: while True: sure=input("\nPyDB>Are you sure to delete?This database is not empty!(Y/N)\nDelete>") if sure=='Y' or sure=='y': shutil.rmtree('PyDB/Database/'+admin+'/'+del_base) print('Success> Successfully deleted this database!') if maindatabase==del_base: maindatabase='' break elif sure=='N' or sure=='n': print('PyDB> Cancel deletion.\n') break
还是老方法,先用listdir判断这个数据库是否存在,如若存在,在判断这是不是个空数据库。如果是,那就是直接删掉;如果不是,则会提示这个数据库不为空,是否确定删除?确定了,那就用shutil的mrtree方法,循环删除数据库内的内容。
今天的最后一个功能,也是数据库最核心的功能:插入数据
elif user_e=="@insert": if maindatabase=='': print("PyDB>Please choose a database first!") else: insert_table=input("PyDB>Please choose a table.\nInsert>") find=os.listdir(User_database_path+'/'+maindatabase) yesorno=False for i in find: if i==insert_table+'.json': yesorno=True if yesorno==False: print("Error>Sorry, this form does not exist.\n") else: toshow=turn(User_database_path+'/'+maindatabase+'/'+insert_table+'.json')[0] toshow=str(toshow).replace('{','') toshow=toshow.replace('}','') toshow=toshow.replace("'",'') print("PyDB>The titles of the columns are |"+toshow+'|.') toinsert=input("PyDB>Please enter the data to insert!\nInsert>") toinsert=toinsert.split(',') toshow=turn(User_database_path+'/'+maindatabase+'/'+insert_table+'.json')[0] listshow=list(toshow) tosave={} if len(toinsert)==len(listshow): for i in range(len(list(toshow))): head=toshow[listshow[i]] tosave.setdefault(head,toinsert[i]) waytos=input("PyDB>Please choose the way to insert!\nInsert>") if waytos=='end': try: saveToJSON(tosave,'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') print("Success>Successfully inserted data!\n") except: print("Error>There is some thing wrong with saving it!\n") elif waytos=='top': try: lastin=turn(User_database_path+'/'+maindatabase+'/'+insert_table+'.json') with open(User_database_path+'/'+maindatabase+'/'+insert_table+'.json',mode='w',encoding='utf-8') as f: json.dump(lastin[0],f) lastin.pop(0) saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(tosave,'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') for i in range(len(lastin)): saveToJSON(lastin[i],'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') print("Success>Successfully inserted data!\n") except: print("Error>There is some thing wrong with saving it!\n") elif len(turn(User_database_path+'/'+maindatabase+'/'+insert_table+'.json'))==int(waytos): try: saveToJSON(tosave,'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') print("Success>Successfully inserted data!\n") except: print("Error>There is some thing wrong with saving it!\n") elif int(waytos)==1: try: lastin=turn(User_database_path+'/'+maindatabase+'/'+insert_table+'.json') with open(User_database_path+'/'+maindatabase+'/'+insert_table+'.json',mode='w',encoding='utf-8') as f: json.dump(lastin[0],f) lastin.pop(0) saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(tosave,'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') for i in range(len(lastin)): saveToJSON(lastin[i],'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') print("Success>Successfully inserted data!\n") except: print("Error>There is some thing wrong with saving it!\n") elif 1<int(waytos)<len(turn(User_database_path+'/'+maindatabase+'/'+insert_table+'.json')): inwaytos=int(waytos) try: lastin=turn(User_database_path+'/'+maindatabase+'/'+insert_table+'.json') with open(User_database_path+'/'+maindatabase+'/'+insert_table+'.json',mode='w',encoding='utf-8') as f: json.dump(lastin[0],f) for i in range(inwaytos): lastin.pop(i) saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(tosave,'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') for i in range(len(lastin)): saveToJSON(lastin[i],'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') print("Success>Successfully inserted data!\n") except: print("Error>There is some thing wrong with saving it!\n") else: print('Error>The information entered is incorrect!\n')
插入数据呢分为三种方式……详细呢,我们下节再介绍,嘿嘿嘿~~
(其实python代码的可读性还是很高的,主要还是靠自己阅读代码,就和语文的阅读理解一样,多读才能提高水平~~好吧,说白了就是我懒QwQ)
import json import os import sys import time import shutil #----------------------- def turn(file): with open(file,mode='r',encoding='utf-8') as f: a=f.readline() a=a.split('","') b=[] for i in range(len(a)): if i <= len(a)-2: b.append(json.loads(a[i])) return b def saveToJSON(dicObject,file): flag=False '''if type(dicObject)!=dict: print('dict') return flag''' try: j_file=open("./PyDB/"+file,'a') json.dump(dicObject,j_file,ensure_ascii=False) flag=True except: print('写数据出错!') finally: if flag: j_file.close() return flag #========================= def GetFromJSON(filename): flag=False dicObject={} try: way="./PyDB/"+filename j_file=open(way,'r') dicObject=json.load(j_file) flag=True except: flag=False finally: if flag: j_file.close() elif flag==False: return False return dicObject #---------------------------------------- def DBhelp(): print("Command list:") print("|Command |Explain |") print("-----------------------------------------------------------------------") print("|@choose |Choose a database to use. |") print("|@create table |Generate a table under the current database. |") if host["Jurisdiction"]=="Root" or host["Jurisdiction"]=="Hang Jiayu": print("|@create user |Create a new user. |") print("|@c or @continue |Clear the current input statement. |") print("|@create database |Create a database according to the boot. |") print("|@del table |Delete a table. |") print("|@del database |Delete a database. |") print("|@exit |Exit the program. |") print("|@h or @help |Get the command list. |") print("|@insert |Insert data into a table. |") print("|@show users |View all users. |") print("|@show tables |View tables under the current database. |") print("|@show database |View the database under the current user. |") print("|@query data |Query data in the selected table. |") print() #---------------------------------------- if __name__ == '__main__': print("| Welcome to PyDB Monitor.") print("| Server version: 1.0.0 PyDB Server.") print("| Add '@' at the beginning of the statement.") print("| Type '@help' or '@h' for help.Type '@continue' or '@c' to clear the current input statement.\n") print("PyDB>Welcome to PyDB!"+"\n") folder='' for i in range(len(os.listdir())): a=os.listdir() if a[i]=='PyDB': folder='PyDB' if folder!='PyDB': os.makedirs('./PyDB'+'./user') os.makedirs('./PyDB'+'./DataBase') #----------------------------------------------------Sing in while True: if len(os.listdir('./PyDB/user'))==0: print("PyDB> There are no users yet :( ... Let's create one! :) \n") admin=input("PyDB> Please enter your User Name!\nAdministrator>") Pass=input("PyDB> Please enter your password!\nPassword>") RePass=input("PyDB> Please enter your password again!\nPassword>") if Pass==RePass: info={ 'Name':admin,'Password':Pass,'Jurisdiction':'Root' } saveToJSON(info,'user/'+admin+'.json') print("\nSuccess>Congratulations, account creation succeeded!\n") host=GetFromJSON("user/"+admin+".json") os.makedirs('./PyDB'+'./DataBase'+'./'+admin) break else: while True: print('PyDB>The two passwords you entered are different. Please try again.') Pass=input("PyDB> Please enter your password!\nPassword>") RePass=input("PyDB> Please enter your password again!\nPassword>") if Pass==RePass: info={ 'User':admin,'Password':Pass,'Jurisdiction':'Root' } saveToJSON(info,'user/'+admin+'.json') print("\nSuccess>Congratulations, account creation succeeded!\n") host=GetFromJSON("user/"+admin+".json") os.makedirs('./PyDB'+'./DataBase'+'./'+admin) break break else: while True: admin=input('User name>') if admin=="@exit": print("PyDB>Thank you for your use~ :) Bye!") time.sleep(3) sys.exit() if GetFromJSON("user/"+admin+".json")==False: print("Error>Sorry, there is no such user.Please try again.") else: host=GetFromJSON("user/"+admin+".json") break Pass=input('Password>') if Pass=="@exit": print("PyDB>Thank you for your use~ :) Bye!") time.sleep(3) sys.exit() if host["Password"]!=Pass: print("Error>Password error, please try again!") Pass=input('Password>') host=GetFromJSON("user/"+admin+".json") if host["Password"]!=Pass: print("Error>Password error, please try again!") Pass=input('Password>') host=GetFromJSON("user/"+admin+".json") if host['Password']!=Pass: print("Error>You have made three consecutive errors. Please try again later.") time.sleep(3) sys.exit() else: print("\n"+"PyDB>Welcome,"+admin+'!\n') break else: print("\n"+"PyDB>Welcome,"+admin+'!\n') break else: print("\n"+"PyDB>Welcome,"+admin+'!\n') break jurisdiction=host["Jurisdiction"] maindatabase='' #-----------------------------------------------------------Console while True: user_e=input('PyDB>') User_database_path="PyDB/DataBase/"+admin #----------------------------------------------Help if user_e=='@h' or user_e=='@help': DBhelp() #----------------------------------------------continue if user_e=='@c' or user_e=='@continue': continue #----------------------------------------------Exit elif user_e=='@exit': print("PyDB>Thank you for your use~ :) Bye!") time.sleep(3) sys.exit() #----------------------------------------------Choose Database elif user_e=='@choose': maindatabase=input('Select>') find=os.listdir(User_database_path) yesorno=False for i in find: if i==maindatabase: yesorno=True if yesorno==False: print("Error>This database does not exist.\n") else: print('PyDB>Database changed.\n') #----------------------------------------------Show Database elif user_e=="@show database": database_num=os.listdir(User_database_path) databases='' if database_num==[]: print("PyDB>There is no database yet. Use '@create database' to create one!\n") else: for i in range(len(database_num)): if i<len(database_num)-1: databases+=database_num[i]+',' else: databases+=database_num[i] print(" | "+databases+' |') #----------------------------------------------Create Database elif user_e=="@create database": database_num=os.listdir(User_database_path) basename=input("PyDB>Please enter the Name of the Database.\nCreate>") os.makedirs('./PyDB'+'./DataBase'+'./'+admin+'./'+basename) print("Success>Database creation succeeded!\n") #----------------------------------------------Create Table elif user_e=="@create table": if maindatabase=='': print("PyDB>Please choose a database first!\n") else: tablename=input('PyDB>Please enter the name of the table.\nCreate>') database_path=os.listdir('PyDB/Database/'+admin+'/'+maindatabase) yesorno=False for i in database_path: i=i.replace(".json",'') if i==tablename: yesorno=True if yesorno==True: print("Error>This table already exists.\n") else: columns=input("PyDB>Please enter the title of each column.\nCreate>") columns=columns.split(',') column_dict={} for i in range(len(columns)): column_dict.setdefault(str(i+1),columns[i]) print("Success>Successfully created the table!\n") saveToJSON(column_dict,'Database/'+admin+'/'+maindatabase+'/'+tablename+'.json') saveToJSON(',','Database/'+admin+'/'+maindatabase+'/'+tablename+'.json') #----------------------------------------------show tables elif user_e=="@show tables": if maindatabase=='': print("PyDB>Please choose a database first!\n") else: database_path=os.listdir('PyDB/Database/'+admin+'/'+maindatabase) if database_path==[]: print("PyDB>There is no table yet. Use '@create table' to create one!\n") else: show_tables='' for i in range(len(database_path)): toshow=database_path[i] if i<len(database_path)-1: show_tables+=toshow.replace('.json','')+',' else: show_tables+=toshow.replace('.json','') print(' |'+show_tables+' |\n') #----------------------------------------------delete database elif user_e=="@del database": del_base=input("PyDB>Please enter the name of the database to delete.\nDelete>") database_path=os.listdir('PyDB/Database/'+admin) yesorno=False for i in database_path: if i==del_base: yesorno=True if yesorno==False: print("Error>This database doesn't exists.\n") else: database_path=os.listdir('PyDB/Database/'+admin+'/'+del_base) if database_path==[]: if maindatabase==del_base: maindatabase='' os.rmdir('PyDB/Database/'+admin+'/'+del_base) print("Success> Successfully deleted this database!\n") else: while True: sure=input("\nPyDB>Are you sure to delete?This database is not empty!(Y/N)\nDelete>") if sure=='Y' or sure=='y': shutil.rmtree('PyDB/Database/'+admin+'/'+del_base) print('Success> Successfully deleted this database!') if maindatabase==del_base: maindatabase='' break elif sure=='N' or sure=='n': print('PyDB> Cancel deletion.\n') break #----------------------------------------------insert data elif user_e=="@insert": if maindatabase=='': print("PyDB>Please choose a database first!") else: insert_table=input("PyDB>Please choose a table.\nInsert>") find=os.listdir(User_database_path+'/'+maindatabase) yesorno=False for i in find: if i==insert_table+'.json': yesorno=True if yesorno==False: print("Error>Sorry, this form does not exist.\n") else: toshow=turn(User_database_path+'/'+maindatabase+'/'+insert_table+'.json')[0] toshow=str(toshow).replace('{','') toshow=toshow.replace('}','') toshow=toshow.replace("'",'') print("PyDB>The titles of the columns are |"+toshow+'|.') toinsert=input("PyDB>Please enter the data to insert!\nInsert>") toinsert=toinsert.split(',') toshow=turn(User_database_path+'/'+maindatabase+'/'+insert_table+'.json')[0] listshow=list(toshow) tosave={} if len(toinsert)==len(listshow): for i in range(len(list(toshow))): head=toshow[listshow[i]] tosave.setdefault(head,toinsert[i]) waytos=input("PyDB>Please choose the way to insert!\nInsert>") if waytos=='end': try: saveToJSON(tosave,'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') print("Success>Successfully inserted data!\n") except: print("Error>There is some thing wrong with saving it!\n") elif waytos=='top': try: lastin=turn(User_database_path+'/'+maindatabase+'/'+insert_table+'.json') with open(User_database_path+'/'+maindatabase+'/'+insert_table+'.json',mode='w',encoding='utf-8') as f: json.dump(lastin[0],f) lastin.pop(0) saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(tosave,'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') for i in range(len(lastin)): saveToJSON(lastin[i],'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') print("Success>Successfully inserted data!\n") except: print("Error>There is some thing wrong with saving it!\n") elif len(turn(User_database_path+'/'+maindatabase+'/'+insert_table+'.json'))==int(waytos): try: saveToJSON(tosave,'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') print("Success>Successfully inserted data!\n") except: print("Error>There is some thing wrong with saving it!\n") elif int(waytos)==1: try: lastin=turn(User_database_path+'/'+maindatabase+'/'+insert_table+'.json') with open(User_database_path+'/'+maindatabase+'/'+insert_table+'.json',mode='w',encoding='utf-8') as f: json.dump(lastin[0],f) lastin.pop(0) saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(tosave,'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') for i in range(len(lastin)): saveToJSON(lastin[i],'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') print("Success>Successfully inserted data!\n") except: print("Error>There is some thing wrong with saving it!\n") elif 1<int(waytos)<len(turn(User_database_path+'/'+maindatabase+'/'+insert_table+'.json')): inwaytos=int(waytos) try: lastin=turn(User_database_path+'/'+maindatabase+'/'+insert_table+'.json') with open(User_database_path+'/'+maindatabase+'/'+insert_table+'.json',mode='w',encoding='utf-8') as f: json.dump(lastin[0],f) for i in range(inwaytos): lastin.pop(i) saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(tosave,'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') for i in range(len(lastin)): saveToJSON(lastin[i],'DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') saveToJSON(',','DataBase/'+admin+'/'+maindatabase+'/'+insert_table+'.json') print("Success>Successfully inserted data!\n") except: print("Error>There is some thing wrong with saving it!\n") else: print('Error>The information entered is incorrect!\n')
(PS:其中一段代码有个小细节哦~找到的人在评论区打出来吧~)