需求:输入用户编号或者用户名,进行查询用户信息,根据编号可以进行精确查询,根据用户名进行模糊查询
思维导图:
#!/usr/bin/env python
#coding:utf-8
import re
import MySQLdb.cursors
conn=MySQLdb.connect(user='root',passwd='123456',host='192.168.2.71',db='login',cursorclass = MySQLdb.cursors.DictCursor)
cur=conn.cursor()
cur.execute("select * from user_account")
user_names=cur.fetchall()
user_list=[] #用于精确查询
name_list=[] #以列表的形式保存用户名
for usernum in user_names:
id_nau = int(usernum['compan_num'])
user_list.append(id_nau)
names =usernum['name']
name_list.append(names)
while True:
id_nau = raw_input("please input your's id or account:").strip()
pattern = ''.join(id_nau)
regex = re.compile(pattern)
count_names = [] #进行模糊匹配用户
for item in name_list:
match = regex.search(item)
if match:
count_names.append(item)
if len(id_nau) ==0: #输入不为空
print "Username cannot be empty!"
continue
for id_nau in count_names:
print "Match Item: %s" % id_nau
print user_names[name_list.index(id_nau)]
continue
try:
if int(id_nau) in user_list:
print user_names[user_list.index(int(id_nau))]
continue
except:
continue
数据库设计:
效果图: