Python: an instance that simulates employee information database operations, and a python employee

Source: Internet
Author: User
Tags file info

Python: an instance that simulates employee information database operations, and a python employee

1. Features

This program simulates the operations on employee information database, and enters commands according to the syntax to add, delete, modify, and query employee information.

2. Implementation Method

• Architecture:

This program is written in python. The key lies in instruction parsing and execution. Instruction parsing mainly uses regular expressions to efficiently match valid information; command Execution is implemented by executing a commd_exe main function and adding, deleting, modifying, and querying four sub-execution functions. The operation method is to use the object-oriented method to visualize employee information, this makes all operations easy and efficient. The main functions of the program are as follows:

(1) command_exe (command)

The command executes the main function, identifies the operation based on the first field of the command, and distributes the operation to the corresponding processing function for execution.

(2) add (command)

Add an employee record function. The command must contain all information except the ID number of the newly added employee. After the program is executed, the information is written to the last row of the employee information table, the ID number is increased by 1 Based on the ID number of the last record.

(3) delete (command)

The employee record deletion function searches for records to be deleted based on the where condition and deletes the records from the information table.

(4) update (command)

Modify and update the employee record function, search for records to be updated based on the where condition, and modify and update the specified information based on the equation after set.

(5) search (command)

Query the employee record function. The corresponding records are queried Based on the where condition. The specified information of the record is displayed based on the select keyword. If it is *, all information of the record is displayed.

(6) verify (staff_temp, condition)

The employee information verification function is used to pass in an object-oriented employee record and the where condition string in the instruction to determine whether the record meets the condition. If yes, True is returned. Otherwise, False is returned. This function is called when the command contains the where field for deletion, modification, and query operations.

(7) logic_cal (staff_temp, logic_exp)

The operation function of a single logical expression, passing in an employee record of an object and a single expression separated by and, or, and not from the where condition string, implement =, >,<, >=, <=, like, and so on. The return result is True or False.

• Main operations:

The data record contains six keywords: id, name, age, phone, dept, enroll_date

Logical operators available for commands: <, >,=, <=, >=, like, and, or, not

Database Operations:

1. add to xxxx values xxxx)

Example: add to staff_table values Alex Li, 22,13651054608, IT, 2013-04-01

2. delete (delete from xxxx where xxxx)

Example: delete from staff_table where age <= 18 and enroll_date like "2017"

3. update xxxx set xxxx where xxxx)

Example:

Update staff_table set dept = "Market", age = 30 where dept = "IT" and phone like "189"

4. Query (select xxxx from xxxx where xxxx)

Example 1:

Select * from staff_table where age> = 25 and not phone like "136" or name like "Li"

Example 2:

Select name, age, dept from db.txt where id <9 and enroll_date like "-05 -"

Example 3: select * from staff_table where * # Show All records

• Use Files:

Staff_table

Store the employee information table as a simulated database file. Each record contains the id, name, age, phone, dept, and enroll_date items, such as "1, Alex Li, 13651054608, IT, 2013-04-0 ".

3. Flowchart

4. Code

#! Usr/bin/env python3 # _ * _ coding: UTF-8 _ * _ 'staff infomation management module '_ author __= 'byron Li ''' ------------------------------------------------ employee information database operation instruction syntax contains six keywords: id, logical operators available for the name, age, phone, dept, and enroll_date commands: <, >,=, <=, >=, like, and, or, not1. add to xxxx values xxxx example: add to staff_table values Alex Li, 13651054608, IT. delete (delete from xxxx Where xxxx) Example: delete from staff_table where age <= 18 and enroll_date like "2017" 3. update xxxx set xxxx where xxxx: update staff_table set dept = "Market", age = 30 where dept = "IT" and phone like "189" 4. query (select xxxx from xxxx where xxxx) Example 1: select * from staff_table where age> = 25 and not phone like "136" or name like "Li" Example 2: select name, age, dept from db.txt where id <9 and enroll_date like "-05 -" Example 3: select * from staff_table where * # display all records ''' import reimport osclass staff (object): # employee class def _ init _ (self, * args): # employee information initialization: assign a value to self from the string list. id = args [0] self. name = args [1] self. age = args [2] self. phone = args [3] self. dept = args [4] self. enroll_date = args [5] self. allinfo = ','. join (args) def Update (self, ** kwargs): # update employee information: Assign the value of if 'id' in kwargs: self from the dictionary parameter. id = kwargs ['id'] if 'name' in kwargs: self. name = kwargs ['name'] if 'age' in kwargs: self. age = kwargs ['age'] if 'phone' in kwargs: self. phone = kwargs ['phone'] if 'dept' in kwargs: self. dept = kwargs ['dept'] if 'roll _ date' in kwargs: self. enroll_date = kwargs ['roll _ date'] self. allinfo = ','. join (map (str, [self. id, self. name, self. age, se Lf. phone, self. dept, self. enroll_date]) def print_info (self, info): # employee information display: the input parameter is "*" or several Keywords of the data record if info = '*': print (self. allinfo) else: info = info. split (',') res = [] for I in info: if hasattr (self, I. strip (): res. append (str (getattr (self, I. strip () print (','. join (res) def command_exe (command): # The command executes the main function, identifies the operation based on the first field of the command, and distributes the operation to the corresponding processing function to execute command = command. strip () return {'add': add, 'delete': delete, 'U Pdate': update, 'select': search ,}. get (command. split () [0], error) (command) def error (command): # error message function. If the command is not syntactically called, print ('\ 033 [31; 1 MB syntax error. Please enter it again! \ 033 [0m \ n') def add (command): # add employee record function command_parse = re. search (r'add \ s *? To \ s (.*?) Values \ s (. *) ', command) # Regular Expression command Parsing if (command_parse): data_file = command_parse.group (1 ). strip () # database file info = command_parse.group (2 ). strip () # new employee information, excluding id = 1 # New Employee id. The default value is 1. In this case, 1 with open (data_file, 'r + ', encoding = 'utf-8') as fr: line = fr. readline () while (line): if line. strip () = '': fr. seek (fr. tell ()-len (line)-2) # locate the beginning of the last line of the file (with only null characters) break staff_temp = staff (* line. strip (). split (',') # convert the read information For the staff Object id = int (staff_temp.id) + 1 # the last row employee id plus 1 is the new employee id line = fr. readline () info_new = ''. join ([str (id), ',', info]) # combine id and other information into a complete record fr. write (info_new) fr. write ('\ n') fr. flush () print ("this database \ 033 [31; 1 m new \ 033 [0 m employee information:", info_new) # Add a record to print else: error (command) def delete (command): # The command_parse = re function for deleting employee records. search (r'delete \ s *? From \ s (.*?) Where \ s (. *) ', command) # command to parse if (command_parse): data_file = command_parse.group (1 ). strip () # database file condition = command_parse.group (2 ). strip () # Search Condition data_file_bak = ''. join ([data_file ,'. bak ']) count = 0 # Delete record count staff_list = [] # Delete record employee Object List with open (data_file, 'R', encoding = 'utf-8 ') as fr, \ open (data_file_bak, 'w', encoding = 'utf-8') as fw: for line in fr: staff_temp = staff (* line. strip (). split (',') if (Verify (staff_temp, condition): # verify that the employee information meets the condition count + = 1 staff_list.append (staff_temp) continue fw. write (staff_temp.allinfo) fw. write ('\ n') fw. flush () OS. remove (data_file) OS. rename (data_file_bak, data_file) print ("this database \ 033 [31; 1 m Delete % d \ 033 [0 m employee information, as follows:" % count) for staff_temp in staff_list: staff_temp.print_info ('*') # Delete record print else: error (command) def update (command): # modify and update employee record function command_parse = re. searc H (r'update \ s (.*?) Set \ s (.*?) Where \ s (. *) ', command) # command to parse if (command_parse): data_file = command_parse.group (1 ). strip () # database file info = command_parse.group (2 ). strip () # condition = command_parse.group (3 ). strip () # Search Condition data_file_bak = ''. join ([data_file ,'. bak ']) info = ''. join (['{', info. replace ('=', ':'), '}']) # modify the info = eval (re. sub (R' (\ w +) \ s *: ', R' "\ 1":', info )) # convert the string to the dictionary count = 0 staff_list = [] with open (Data_file, 'R', encoding = 'utf-8') as fr, \ open (data_file_bak, 'w', encoding = 'utf-8') as fw: for line in fr: staff_temp = staff (* line. strip (). split (',') if (verify (staff_temp, condition): # verify that the employee information meets the condition staff_temp.update (** info) # Call the employee object member function to update information count + = 1 staff_list.append (staff_temp) fw. write (staff_temp.allinfo) fw. write ('\ n') fw. flush () OS. remove (data_file) OS. rename (data_file_bak, data_file) print ("Database \ 033 [31; 1 m updated % d items \ 033 [0 m employee information, as follows: "% count) for staff_temp in staff_list: staff_temp.print_info ('*') # update record print else: error (command) def search (command): # query employee record function command_parse = re. search (r'select \ s (. *?) From \ s (.*?) Where \ s (. *) ', command) # command to parse if (command_parse): info = command_parse.group (1 ). strip () # The information to be displayed after the search is complete. "*" indicates the overall display record data_file = command_parse.group (2 ). strip () # database file condition = command_parse.group (3 ). strip () # Search Condition count = 0 staff_list = [] with open (data_file, 'R', encoding = 'utf-8') as fr: for line in fr: staff_temp = staff (* line. strip (). split (',') if (verify (staff_temp, condition): # verify whether the employee information meets the condition count + = 1 staff _ List. append (staff_temp) print ("this database \ 033 [31; 1 m found % d \ 033 [0 m employee information, as follows:" % count) for staff_temp in staff_list: staff_temp.print_info (info) # query record print else: error (command) def verify (staff_temp, condition): # employee information verification function, input an employee object and condition string if condition. strip () = '*': return True # If the condition is '*', that is, all records meet the condition condition_list = condition. split () # Search Condition string to list if len (condition_list) = 0: return False logic_str = ['and', 'or', 'not'] # logical operation A list composed of string and, Or, non-logic_exp = [] # logical expressions of a single condition, such as ['age', '', '>', '= ', 20] or ['dept', '', 'like','', 'hr'] logic_list = [] # list of the calculated results of the expressions of each condition, for example, ['true', 'and', 'false', 'or', 'not', 'false'] for I in condition_list: if I in logic_str: if (len (logic_exp )! = 0): logic_list.append (str (logic_cal (staff_temp, logic_exp) # Calculate the logical expression and convert the returned True or False values into strings and add them to the logic_list.append (I) list) logic_exp = [] else: logic_exp.append (I) logic_list.append (str (logic_cal (staff_temp, logic_exp) return eval (''. join (logic_list) # convert the list to a mathematical expression to complete the logical operation of all conditions. The result is True or Falsedef logic_cal (staff_temp, logic_exp ): # logic_exp = re. search ('(. + ?) ([= <>] {1, 2} | like )(. + )',''. join (logic_exp) # optimize the expression list to three elements, such as ['age', '> =', 20] or ['dept', 'like ', 'hr'] if (logic_exp): logic_exp = list (logic_exp.group (1, 2, 3) if (hasattr (staff_temp, logic_exp [0]): logic_exp [0] = getattr (staff_temp, logic_exp [0]) else: return False if logic_exp [1] = ': # convert '=' in the command to "=" logic_exp [1] = '= 'if logic_exp [1] = 'like ': # return re. search (logic_exp [2]. strip ("'" ). Strip ('"'), logic_exp [0]) and True elif (logic_exp [0]. isdigit () and logic_exp [2]. isdigit (): # Calculate the number at both ends. Convert the eval function to the mathematical expression return eval (''. join (logic_exp) elif (logic_exp [1] = '): # non-numeric operations, that is, string operations. In this case, the logical operator can only be' = ', if the eval function is used, the string is converted into a non-defined variable and cannot be calculated. Therefore, use "=" to calculate return logic_exp [0] = logic_exp [2]. strip ("'"). strip ('"') # Equal string discrimination, while eliminating the impact of the string quotation marks in the instruction, that is, the quotation marks are more than the strings in the record. else: # For output in other non-syntactic condition formats, False return False else: retu is returned directly. Rn Falseif _ name __= = '_ main _': # main function, database command input and execution while (True ): command = input ("Enter the database operation command according to the Syntax:") # enter the command if command = 'exit ': print ("the database operation is complete and exits successfully! ". Center (50, '*') break command_exe (command) # command Execution

The above example of simulating employee information database operations in Python is all the content shared by Alibaba Cloud xiaobian. I hope to give you a reference and support for the help house.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.