Python MySQL公安人员信息管理系统 - 实用教程
该项目需要涉及以下步骤:
-
创建一个名为'police'的数据库。
-
在'police'数据库中创建一个名为'person'的表,包含以下字段:
- id (主键,自增长)
- name (姓名)
- age (年龄)
- gender (性别)
- department (所在部门)
- position (职位)
-
编写Python程序,连接到mysql数据库,并实现以下功能:
- 添加人员信息:向'person'表中插入一条新记录
- 修改人员信息:根据id修改'person'表中的一条记录
- 删除人员信息:根据id删除'person'表中的一条记录
- 查询人员信息:从'person'表中查询符合条件的记录,并输出结果
-
在程序中使用input()函数获取用户输入,实现交互式操作。
下面是一个简单的示例代码:
import mysql.connector
# 连接到数据库
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="police"
)
# 获取游标
mycursor = mydb.cursor()
# 添加人员信息
def add_person():
name = input('请输入姓名:')
age = input('请输入年龄:')
gender = input('请输入性别:')
department = input('请输入所在部门:')
position = input('请输入职位:')
sql = "INSERT INTO person (name, age, gender, department, position) VALUES (%s, %s, %s, %s, %s)"
val = (name, age, gender, department, position)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "条记录已插入。")
# 修改人员信息
def update_person():
id = input('请输入要修改的记录id:')
name = input('请输入姓名:')
age = input('请输入年龄:')
gender = input('请输入性别:')
department = input('请输入所在部门:')
position = input('请输入职位:')
sql = "UPDATE person SET name=%s, age=%s, gender=%s, department=%s, position=%s WHERE id=%s"
val = (name, age, gender, department, position, id)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "条记录已修改。")
# 删除人员信息
def delete_person():
id = input('请输入要删除的记录id:')
sql = "DELETE FROM person WHERE id=%s"
val = (id,)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "条记录已删除。")
# 查询人员信息
def query_person():
name = input('请输入姓名(留空表示不限):')
age = input('请输入年龄(留空表示不限):')
gender = input('请输入性别(留空表示不限):')
department = input('请输入所在部门(留空表示不限):')
position = input('请输入职位(留空表示不限):')
sql = "SELECT * FROM person WHERE 1=1"
if name:
sql += " AND name='%s'" % name
if age:
sql += " AND age='%s'" % age
if gender:
sql += " AND gender='%s'" % gender
if department:
sql += " AND department='%s'" % department
if position:
sql += " AND position='%s'" % position
mycursor.execute(sql)
result = mycursor.fetchall()
for x in result:
print(x)
# 主函数
def main():
while True:
print("请选择操作:")
print("1. 添加人员信息")
print("2. 修改人员信息")
print("3. 删除人员信息")
print("4. 查询人员信息")
print("0. 退出程序")
choice = input("请输入选择:")
if choice == "1":
add_person()
elif choice == "2":
update_person()
elif choice == "3":
delete_person()
elif choice == "4":
query_person()
elif choice == "0":
break
else:
print("无效的选择,请重新输入。")
# 执行主函数
main()
这是一个简单的实现,可以根据具体需求进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/n5Oc 著作权归作者所有。请勿转载和采集!