CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day36-45/code/contact/main.py
Views: 729
1
"""
2
-- 创建名为address的数据库
3
create database address default charset utf8;
4
5
-- 切换到address数据库
6
use address;
7
8
-- 创建联系人表tb_contacter
9
create table tb_contacter
10
(
11
conid int auto_increment comment '编号',
12
conname varchar(31) not null comment '姓名',
13
contel varchar(15) default '' comment '电话',
14
conemail varchar(255) default'' comment '邮箱',
15
primary key (conid)
16
);
17
"""
18
import pymysql
19
20
INSERT_CONTACTER = """
21
insert into tb_contacter (conname, contel, conemail)
22
values (%s, %s, %s)
23
"""
24
DELETE_CONTACTER = """
25
delete from tb_contacter where conid=%s
26
"""
27
UPDATE_CONTACTER = """
28
update tb_contacter set conname=%s, contel=%s, conemail=%s
29
where conid=%s
30
"""
31
SELECT_CONTACTERS = """
32
select conid as id, conname as name, contel as tel, conemail as email
33
from tb_contacter limit %s offset %s
34
"""
35
SELECT_CONTACTERS_BY_NAME = """
36
select conid as id, conname as name, contel as tel, conemail as email
37
from tb_contacter where conname like %s
38
"""
39
COUNT_CONTACTERS = """
40
select count(conid) as total from tb_contacter
41
"""
42
43
44
class Contacter(object):
45
46
def __init__(self, id, name, tel, email):
47
self.id = id
48
self.name = name
49
self.tel = tel
50
self.email = email
51
52
53
def input_contacter_info():
54
name = input('姓名: ')
55
tel = input('手机: ')
56
email = input('邮箱: ')
57
return name, tel, email
58
59
60
def add_new_contacter(con):
61
name, tel, email = input_contacter_info()
62
try:
63
with con.cursor() as cursor:
64
if cursor.execute(INSERT_CONTACTER,
65
(name, tel, email)) == 1:
66
print('添加联系人成功!')
67
except pymysql.MySQLError as err:
68
print(err)
69
print('添加联系人失败!')
70
71
72
def delete_contacter(con, contacter):
73
try:
74
with con.cursor() as cursor:
75
if cursor.execute(DELETE_CONTACTER, (contacter.id, )) == 1:
76
print('联系人已经删除!')
77
except pymysql.MySQLError as err:
78
print(err)
79
print('删除联系人失败!')
80
81
82
def edit_contacter_info(con, contacter):
83
name, tel, email = input_contacter_info()
84
contacter.name = name or contacter.name
85
contacter.tel = tel or contacter.tel
86
contacter.email = email or contacter.email
87
try:
88
with con.cursor() as cursor:
89
if cursor.execute(UPDATE_CONTACTER,
90
(contacter.name, contacter.tel,
91
contacter.email, contacter.id)) == 1:
92
print('联系人信息已经更新!')
93
except pymysql.MySQLError as err:
94
print(err)
95
print('更新联系人信息失败!')
96
97
98
def show_contacter_detail(con, contacter):
99
print('姓名:', contacter.name)
100
print('手机号:', contacter.tel)
101
print('邮箱:', contacter.email)
102
choice = input('是否编辑联系人信息?(yes|no)')
103
if choice == 'yes':
104
edit_contacter_info(con, contacter)
105
else:
106
choice = input('是否删除联系人信息?(yes|no)')
107
if choice == 'yes':
108
delete_contacter(con, contacter)
109
110
111
def show_search_result(con, cursor):
112
contacters_list = []
113
for index, row in enumerate(cursor.fetchall()):
114
contacter = Contacter(**row)
115
contacters_list.append(contacter)
116
print('[%d]: %s' % (index, contacter.name))
117
if len(contacters_list) > 0:
118
choice = input('是否查看联系人详情?(yes|no)')
119
if choice.lower() == 'yes':
120
index = int(input('请输入编号: '))
121
if 0 <= index < cursor.rowcount:
122
show_contacter_detail(con, contacters_list[index])
123
124
125
def find_all_contacters(con):
126
page, size = 1, 5
127
try:
128
with con.cursor() as cursor:
129
cursor.execute(COUNT_CONTACTERS)
130
total = cursor.fetchone()['total']
131
while True:
132
cursor.execute(SELECT_CONTACTERS,
133
(size, (page - 1) * size))
134
show_search_result(con, cursor)
135
if page * size < total:
136
choice = input('继续查看下一页?(yes|no)')
137
if choice.lower() == 'yes':
138
page += 1
139
else:
140
break
141
else:
142
print('没有下一页记录!')
143
break
144
except pymysql.MySQLError as err:
145
print(err)
146
147
148
def find_contacters_by_name(con):
149
name = input('联系人姓名: ')
150
try:
151
with con.cursor() as cursor:
152
cursor.execute(SELECT_CONTACTERS_BY_NAME,
153
('%' + name + '%', ))
154
show_search_result(con, cursor)
155
except pymysql.MySQLError as err:
156
print(err)
157
158
159
def find_contacters(con):
160
while True:
161
print('1. 查看所有联系人')
162
print('2. 搜索联系人')
163
print('3. 退出查找')
164
choice = int(input('请输入: '))
165
if choice == 1:
166
find_all_contacters(con)
167
elif choice == 2:
168
find_contacters_by_name(con)
169
elif choice == 3:
170
break
171
172
173
def main():
174
con = pymysql.connect(host='1.2.3.4', port=3306,
175
user='yourname', passwd='yourpass',
176
db='address', charset='utf8',
177
autocommit=True,
178
cursorclass=pymysql.cursors.DictCursor)
179
while True:
180
print('=====通讯录=====')
181
print('1. 新建联系人')
182
print('2. 查找联系人')
183
print('3. 退出系统')
184
print('===============')
185
choice = int(input('请选择: '))
186
if choice == 1:
187
add_new_contacter(con)
188
elif choice == 2:
189
find_contacters(con)
190
elif choice == 3:
191
con.close()
192
print('谢谢使用, 再见!')
193
break
194
195
196
if __name__ == '__main__':
197
main()
198
199