程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

2022 Python winter vacation advanced training seventh notes

編輯:Python
 send ⽤⾯ The idea of object-oriented programming is to complete the development of student management system , As follows :
System requirements : Student data is stored in ⽂ In the piece system function : Add students 、 Delete student 、 Modify student information 、 Query student information 、 Display all student information 、 Save student information and exit the system
The main function
# 1. guide ⼊managerSystem modular
from managerSystem import *
from Multithreading saves data in real time import *
# 2. Start the student management system
if __name__ == '__main__':
student_manager = StudentManager()
r = MyTheard(1) # Every second , The database submits and saves data
r.start()
student_manager.run()
Function function 
from student import *
import pymysql
class StudentManager(object):
def __init__(self):
# Store student data -- list
self.student_list = []
# One . Program entry function
def run(self):
# 1. Load the student data in the file
self.load_student()
while True:
# 2. Display the function menu
self.show_menu()
# 3. The user enters the target function serial number
menu_num = int(input(' Please enter the function serial number you need :'))
# 4. Perform different functions according to the serial number entered by the user -- If user input 1, Execution add
if menu_num == 1:
# Add students
self.add_student()
elif menu_num == 2:
# Delete student
self.del_student()
elif menu_num == 3:
# Modify student information
self.modify_student()
elif menu_num == 4:
# Query student information
self.search_student()
elif menu_num == 5:
# Display all student information
self.show_student()
# elif menu_num == 6:
# # Save student information
# self.save_student()
elif menu_num == 6:
# Exit the system -- Exit loop
break
# Two . System function
# 2.1 Display the function menu -- Function correspondence of print serial number -- static state
@staticmethod
def show_menu():
print(' Please select the following functions :')
print('1: Add students ')
print('2: Delete student ')
print('3: Modify student information ')
print('4: Query student information ')
print('5: Display all student information ')
# print('6: Save student information ')
print('6: Exit the system ')
# 2.2 Add students
def add_student(self):
# 1. The user enters the name 、 Gender 、 cell-phone number
name = input(' Please enter your name :')
gender = input(' Please enter your major grade :')
tel = input(' Please enter your student number :')
# 2. Create student object -- class ? Class in student In the document First import student modular , Then create the object
student = (name, gender, tel)
try: # Capture exception , Prevent abnormal interruption
# db = pymysql.connect()
db = pymysql.connect(host='localhost', # Host name
user='root', # user name
password='123456', # password
database='mysqlpython1') # database
print(' Database connection successful ')
cur = db.cursor() # Create a cursor
 sql = " INSERT INTO Student (Name,Grade,StudentId) VALUE (%s,%s,%s) "
 # Table name Field Insert content
value = student
# value = (' Jinchuangxiang ', ' Sophomore in software engineering ', 542013460716)
cur.execute(sql, value)
db.commit() # Database commit Finally, submit
print(' Insert the success ')
except pymysql.Error as e: # Capture exception
print(" Insert the failure :" + str(e))
db.rollback() # Database recovery
db.close()
# 3. Add the object to the student list
# self.student_list.append(student)
#
# print(self.student_list)
# print(student)
# 2.3 Delete student
def del_student(self):
# 1. User input target student name
del_name = input(' Please enter the name of the student to delete :')
try: # Capture exception , Prevent abnormal interruption
# db = pymysql.connect()
db = pymysql.connect(host='localhost', # Host name
user='root', # user name
password='123456', # password
database='mysqlpython1') # database
print(' Database connection successful ')
cur = db.cursor() # Create a cursor
 sql = "DELETE FROM Student where Name=%s"
 value = (del_name)
if cur.execute(sql, value):
db.commit()
print(' Delete successful ')
else:
print(' There is no data of this student in the library ')
except pymysql.Error as e: # Capture exception
print(" Delete failed :" + str(e))
db.rollback()
db.close()
# 2. Traverse the student list , If the student entered by the user exists, the student object will be deleted , Otherwise, prompt the students that they do not exist
# for i in self.student_list:
# if del_name == i.name:
# # Delete the student object
# self.student_list.remove(i)
# break
# else:
# # The code executed at the end of the cycle normal price : The loop ends without deleting any objects , Therefore, it means that the target student entered by the user does not exist
# print(' Check no one !')
#
# print(self.student_list)
# 2.4 Modify student information
def modify_student(self):
# 1. User input target student name
modify_name = input(' Please enter the name of the student to be modified :')
try: # Capture exception , Prevent abnormal interruption
# db = pymysql.connect()
db = pymysql.connect(host='localhost', # Host name
user='root', # user name
password='123456', # password
database='mysqlpython1') # database
print(' Database connection successful ')
cur = db.cursor() # Create a cursor
 sql = "SELECT * FROM Student where Name=%s"
 value = (modify_name)
# Table name
# cur.execute(sql,value)
# results = cur.fetchall()
# for row in results:
# Name = row[0] # Creating a tuple
# Grade = row[1]
# StudentId = row[2]
# print('Name:%s,Grade:%s,StudentId:%s' % (Name, Grade, StudentId))
if cur.execute(sql,value):
results = cur.fetchall()
for row in results:
Name = row[0] # Creating a tuple
Grade = row[1]
StudentId = row[2]
print('Name:%s,Grade:%s,StudentId:%s' % (Name, Grade, StudentId))
print(" Please enter new information ")
 Newname = input(' full name :')
Newgender = input(' Professional grade :')
Newtel = input(' Student number :')
 try: # Capture exception , Prevent abnormal interruption
# db = pymysql.connect()
db = pymysql.connect(host='localhost', # Host name
user='root', # user name
password='123456', # password
database='mysqlpython1') # database
print(' Database connection successful ')
 cur = db.cursor() # Create a cursor
sql1 = "UPDATE Student SET Name= %s,Grade= %s,StudentId= %s WHERE Name=%s"
# sql3 = "UPDATE Student SET StudentId= %s WHERE StudentId=%s"
# Table name Field name New content Old content
value1 = (Newname, Newgender, Newtel, modify_name)
cur.execute(sql1, value1)
# value2 = (Newgender, modify_name)
# cur.execute((sql2,value2))
# value3 = (Newtel, modify_name)
# cur.execute((sql2, value3))
db.commit()
print(' The update is successful ')
except pymysql.Error as e: # Capture exception
print(" Update failed :" + str(e))
db.rollback()
db.close() # Database shutdown
else:
print(' Check no one !')
except pymysql.Error as e: # Capture exception
print(" The query fails :" + str(e))
# 2. Traverse list data , If there is a problem, modify the name, gender and mobile phone number , Otherwise, prompt the students that they do not exist
# for i in self.student_list:
# if modify_name == i.name:
# i.name = input(' full name :')
# i.gender = input(' Gender :')
# i.tel = input(' cell-phone number :')
# print(f' Student information modified successfully , full name {i.name}, Gender {i.gender}, cell-phone number {i.tel}')
# break
# else:
# print(' Check no one !')
# 2.5 Query student information
def search_student(self):
# 1. User input target student name
search_name = input(' Please enter the name of the student you want to search :')
try: # Capture exception , Prevent abnormal interruption
# db = pymysql.connect()
db = pymysql.connect(host='localhost', # Host name
user='root', # user name
password='123456', # password
database='mysqlpython1') # database
print(' Database connection successful ')
 cur = db.cursor() # Create a cursor
sql = "SELECT * FROM Student where Name=%s"
value = (search_name)
# Table name
if cur.execute(sql,value):
results = cur.fetchall()
for row in results:
Name = row[0] # Creating a tuple
Grade = row[1]
StudentId = row[2]
print('Name:%s,Grade:%s,StudentId:%s' % (Name, Grade, StudentId))
else:
print(' Check no one !')
except pymysql.Error as e: # Capture exception
print(" The query fails :" + str(e))
db.close() # Database shutdown
# # 2. Traverse the list . Print student information if student exists , Otherwise, prompt the students that they do not exist
# for i in self.student_list:
# if search_name == i.name:
# print(f' Name is {i.name}, Gender is {i.gender}, The cell phone number is {i.tel}')
# break
# else:
# print(' Check no one !')
# 2.6 Display all student information
def show_student(self):
# 1. Print header
# print(' full name \t Gender \t cell-phone number ')
#
# # 2. Print student data
# for i in self.student_list:
# print(f'{i.name}\t{i.gender}\t{i.tel}')
try: # Capture exception , Prevent abnormal interruption
# db = pymysql.connect()
db = pymysql.connect(host='localhost', # Host name
user='root', # user name
password='123456', # password
database='mysqlpython1') # database
print(' Database connection successful ')
cur = db.cursor() # Create a cursor
 sql = "SELECT * FROM Student"
# Table name
cur.execute(sql)
results = cur.fetchall()
 for row in results:
Name = row[0] # Creating a tuple
Grade = row[1]
StudentId = row[2]
print('Name:%s,Grade:%s,StudentId:%s' % (Name, Grade, StudentId))
except pymysql.Error as e: # Capture exception
print(" The query fails :" + str(e))
db.close() # Database shutdown
# 2.7 Save student information
def save_student(self):
# 1. Open file
f = open('student.data', 'w')
# 2. File write data
# 2.1 [ Participants ] convert to [ Dictionaries ]
new_list = [i.__dict__ for i in self.student_list]
# 2.2 File is written to String data
f.write(str(new_list))
# 3. Close file
f.close()
# 2.8 Load student information
def load_student(self):
# 1. Open file : Try r open , If there is any abnormality w
try:
f = open('student.data', 'r')
except:
f = open('student.data', 'w')
else:
# 2. Reading data : The data read from the file is the string restore list type ;[{}] transformation [ Participants ]
data = f.read() # character string
new_list = eval(data)
for i in new_list:
self.student_list = [Student(i['name'], i['gender'], i['tel'])]
# self.student_list = [Student(i['name'], i['gender'], i['tel']) for i in new_list]
finally:
# 3. Close file
f.close()

 Students
class Student(object):
def __init__(self, name, gender, tel):
self.name = name
self.gender = gender
self.tel = tel
def __str__(self):
return f'{self.name}, {self.gender}, {self.tel}'

Save the database every second

import threading
import time
import pymysql
try: # Capture exception , Prevent abnormal interruption
# db = pymysql.connect()
db = pymysql.connect(host='localhost', # Host name
user='root', # user name
password='123456', # password
database='mysqlpython1') # database
except pymysql.Error as e: # Capture exception
print(" Database connection failed :" + str(e))
# The second way to create a thread Create a class
class MyTheard(threading.Thread):
def __init__(self,n):
super(MyTheard, self).__init__()
self.n = n
def run(self):
while True:
db.commit()
time.sleep(1)

(8 Bar message ) classic SQL Corpus of sentences _ Learning notes -CSDN Blog _sql Corpus of sentences

(8 Bar message ) Databases are commonly used sql Sentence summary _Ace_2 The blog of -CSDN Blog _ Databases are commonly used sql sentence


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved