python写一个通讯录step by step V3.0
更新功能:
数据库进行数据存入和读取操作
字典配合函数调用实现switch功能
其他:函数、字典、模块调用
注意问题:
-
1、更优美的格式化输出
-
2、把日期换算成年龄
-
3、更新操作做的更优雅
准备工作
db准备
-
创建数据库
mysql> create database txl charset utf8; Query OK, 1 row affected (0.09 sec) mysql>
-
创建表
mysql> use txl; Database changed mysql> create table tb_txl (id int auto_increment primary key,name char(20),gender char(1),brithday date,tel char(20)); Query OK, 0 rows affected (0.29 sec) mysql> desc tb_txl; +----------+----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+----------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | char(20) | YES | | NULL | | | gender | char(1) | YES | | NULL | | | brithday | date | YES | | NULL | | | tel | char(20) | YES | | NULL | | +----------+----------+------+-----+---------+----------------+
开始
1、模板准备
相对于V1、V2、V3版本的,模板基本一致
-
模板
#!/usr/bin/env python #coding:utf8 #Author:zhuima #Date:2015-03-30 #Version:0.1 #Function:display a list and add date # 导入模块 import os def menu(): '''设置munu目录,提供给用户的操作接口 ''' print ''' 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program ''' op = raw_input('Please select one >>> ') return op def txl_exit(): ''' 退出程序 ''' os._exit(0) def txl_error(): ''' 当用户输出选项不在定义的选项内的时候,报错''' print print 'Unkonw options,Please try again!' # 定义dict,配合函数实现switch功能 ops = { # '1':txl_add, # '2':txl_dis, # '3':txl_update, # '4':txl_del, # '5':txl_sort, '0':txl_exit, } def main(): '''主程序 ''' while True: op = menu() ops.get(op,txl_error)() if __name__ == '__main__': main()
2、db_config准备
使用db配置单独生产一个配置文件,直接以模块的形式调用即可
-
db_config配置文件(调用数据库的好方法,值得借鉴)
[root@mysql01 day0330]# cat db_config.py import MySQLdb db_config = { 'host' : 'localhost', 'user' : 'root', 'passwd' : 'zhuima', 'charset' : 'utf8', 'db': 'txl', } conn = MySQLdb.connect(**db_config) cursor = conn.cursor()
3、连接数据库,实现增,查功能
导入db_config模块中的conn和cursor,然后直接使用
-
代码片段
#确保自定义模块能够被正常导入 import sys module_path = '/zhuima' sys.path.append(module_path) # 导入自定义模块 from db_config import conn,cursor .... def txl_add(): '''读取用户输入信息,并写入数据库''' name = raw_input('Please enput your name: ') gender = raw_input('Please enput your gender: ') brithday = raw_input('like (YYYY-MM-DD) >>> ') tel = raw_input('Please enput your tel: ') sql = 'insert into tb_txl values (null,%s,%s,%s,%s)' cursor.execute(sql,(name,gender,brithday,tel)) conn.commit() def txl_dis(): '''从数据库中提取信息,然后打印出来 ''' sql = 'select name,gender,brithday,tel from tb_txl' cursor.execute(sql) info = cursor.fetchall() #print "%s\t%s\t%s\t%s" % info if len(info) > 0: print "name\tgender\tbrithday\ttel" print "---------------------------" #print info # 这里打印出来的结果未作处理 for x in info: print x else: print print ">>> Empty,There is no user info in db <<<" #print info def txl_exit(): '''关闭连接, 退出程序 ''' cursor.close() conn.close() os._exit(0)
-
导入模块测试
(如果db_config和当前脚本不在同一个目录下面,要设定path才行)[root@mysql01 day0330]# python v3_1.py 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name gender brithday tel --------------------------- ((u'zhuima', u'f', datetime.date(1988, 12, 8), u'10086'),) 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 1 Please enput your name: nick Please enput your gender: m like (YYYY-MM-DD) >>> 1990-10-10 Please enput your tel: 10010 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name gender brithday tel --------------------------- (u'zhuima', u'f', datetime.date(1988, 12, 8), u'10086') (u'nick', u'm', datetime.date(1990, 10, 10), u'10010') 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 0
4、连接数据库,实现删功能
导入db_config模块中的conn和cursor,然后直接使用
-
代码片段
def txl_del(): status = True name = raw_input('Delete Information By Name >>> ') select_sql = 'select name from tb_txl' cursor.execute(select_sql) info = cursor.fetchall() print info for line in info: if name in line: status = False delete_sql = 'delete from tb_txl where name=%s' cursor.execute(delete_sql,(name,)) conn.commit() if status: print print ">>>Unkonw User,Please Try again! <<<"
-
测试结果
(中间添加了print来调试代码)[root@mysql01 day0330]# python v3_1.py 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name gender brithday tel ------------------------------------ (u'zhuima', u'f', datetime.date(1988, 12, 8), u'10086') (u'kale', u'f', datetime.date(1988, 2, 18), u'10032') 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 4 Delete Information By Name >>> kale ((u'zhuima',), (u'kale',)) 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 2 name gender brithday tel ------------------------------------ (u'zhuima', u'f', datetime.date(1988, 12, 8), u'10086') 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 4 Delete Information By Name >>> sdfsdf ((u'zhuima',),) >>>Unkonw User,Please Try again! <<< 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:sort user info by 0.exit program Please select one >>> 0
5、连接数据库,实现更新功能
根据用户名搜索相关的值来进行更新
-
update实例演示
mysql> select * from tb_txl; +----+--------+--------+------------+-------+ | id | name | gender | brithday | tel | +----+--------+--------+------------+-------+ | 1 | zhuima | f | 1988-12-08 | 10086 | | 6 | nick | m | 1990-10-06 | 10011 | +----+--------+--------+------------+-------+ 2 rows in set (0.00 sec) mysql> update tb_txl set tel='10010' where name='nick'; Query OK, 1 row affected (0.22 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from tb_txl; +----+--------+--------+------------+-------+ | id | name | gender | brithday | tel | +----+--------+--------+------------+-------+ | 1 | zhuima | f | 1988-12-08 | 10086 | | 6 | nick | m | 1990-10-06 | 10010 | +----+--------+--------+------------+-------+ 2 rows in set (0.00 sec) mysql>
-
代码片段
def txl_update(): statue = True name = raw_input('Update Information By Name >>> ') select_sql = 'select name from tb_txl' cursor.execute(select_sql) info = cursor.fetchall() for line in info: if name in line: status = False gender = raw_input('Update Your Gender for %s >>> ' % name) brithday = raw_input('Update Your Brithday like (YYYY-MM-DD) for %s >>> ' % name) tel = raw_input('Update Your Tel for %s >>> '% name) update_sql = 'update tb_txl set gender=%s,brithday=%s,tel=%s where name=%s' cursor.execute(update_sql,(gender,brithday,tel,name,)) conn.commit() if status: print print ">>>Unkonw User,Please Try again! <<<"
-
执行结果
[root@mysql01 day0330]# python v3_1.py 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:check user info by username 0.exit program Please select one >>> 2 name gender brithday tel ------------------------------------ (u'nick', u'm', datetime.date(1990, 10, 6), u'10010') (u'zhuima', u'f', datetime.date(1988, 12, 8), u'10086') 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:check user info by username 0.exit program Please select one >>> 3 Update Information By Name >>> zhuima Update Your Gender for zhuima >>> m Update Your Brithday like (YYYY-MM-DD) for zhuima >>> 1990-10-10 Update Your Tel for zhuima >>> 10000 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:check user info by username 0.exit program Please select one >>> 2 name gender brithday tel ------------------------------------ (u'nick', u'm', datetime.date(1990, 10, 6), u'10010') (u'zhuima', u'm', datetime.date(1990, 10, 10), u'10000') 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:check user info by username 0.exit program Please select one >>> 5 Enter The name >>> sdfsdf >>>Unkonw User,Please Try again! <<<
6、连接数据库,实现检索功能
根据用户名搜索相关的值然后返显结果
-
代码片段
def txl_check(): status = True name = raw_input('Enter The name >>> ') cursor.execute('select * from tb_txl') info = cursor.fetchall() for line in info: if name in line: status = False print line if status: print print ">>>Unkonw User,Please Try again! <<<"
-
测试结果
[root@mysql01 day0330]# python v3_1.py 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:check user info by username 0.exit program Please select one >>> 5 Enter The name >>> sdfs >>>Unkonw User,Please Try again! <<< 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:check user info by username 0.exit program Please select one >>> 5 Enter The name >>> nick (6L, u'nick', u'm', datetime.date(1990, 10, 6), u'10010') 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:check user info by username 0.exit program Please select one >>>
完整代码
#!/usr/bin/env python #coding:utf8 #Author:zhuima #Date:2015-03-22 #Version:0.1 #Function:display a list and add date # 导入模块 import os #确保自定义模块能够被正常导入 import sys module_path = '/zhuima' sys.path.append(module_path) # 导入自定义模块 from db_config import conn,cursor def menu(): '''设置munu目录,提供给用户的操作接口 ''' print ''' 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:check user info by username 0.exit program ''' op = raw_input('Please select one >>> ') return op def txl_add(): '''读取用户输入信息,并写入数据库''' name = raw_input('Please enput your name: ') gender = raw_input('Please enput your gender: ') brithday = raw_input('like (YYYY-MM-DD) >>> ') tel = raw_input('Please enput your tel: ') sql = 'insert into tb_txl values (null,%s,%s,%s,%s)' cursor.execute(sql,(name,gender,brithday,tel)) conn.commit() def txl_dis(): '''从数据库中提取信息,然后打印出来 ''' sql = 'select name,gender,brithday,tel from tb_txl' cursor.execute(sql) info = cursor.fetchall() #print "%s\t%s\t%s\t%s" % info if len(info) > 0: print "name\tgender\tbrithday\ttel" print "------------------------------------" #print info for x in info: print x else: print print ">>> Empty,There is no user info in db <<<" #print info def txl_del(): status = True name = raw_input('Delete Information By Name >>> ') select_sql = 'select name from tb_txl' cursor.execute(select_sql) info = cursor.fetchall() for line in info: if name in line: status = False delete_sql = 'delete from tb_txl where name=%s' cursor.execute(delete_sql,(name,)) conn.commit() if status: print print ">>>Unkonw User,Please Try again! <<<" def txl_update(): statue = True name = raw_input('Update Information By Name >>> ') select_sql = 'select name from tb_txl' cursor.execute(select_sql) info = cursor.fetchall() for line in info: if name in line: status = False gender = raw_input('Update Your Gender for %s >>> ' % name) brithday = raw_input('Update Your Brithday like (YYYY-MM-DD) for %s >>> ' % name) tel = raw_input('Update Your Tel for %s >>> '% name) update_sql = 'update tb_txl set gender=%s,brithday=%s,tel=%s where name=%s' cursor.execute(update_sql,(gender,brithday,tel,name,)) conn.commit() if status: print print ">>>Unkonw User,Please Try again! <<<" def txl_check(): status = True name = raw_input('Enter The name >>> ') cursor.execute('select * from tb_txl') info = cursor.fetchall() for line in info: if name in line: status = False print line if status: print print ">>>Unkonw User,Please Try again! <<<" def txl_exit(): ''' 退出程序 ''' cursor.close() conn.close() os._exit(0) def txl_error(): ''' 当用户输出选项不在定义的选项内的时候,报错''' print print 'Unkonw options,Please try again!' # 定义dict,配合函数实现switch功能 ops = { '1':txl_add, '2':txl_dis, '3':txl_update, '4':txl_del, '5':txl_check, '0':txl_exit, } def main(): '''主程序 ''' while True: op = menu() ops.get(op,txl_error)() if __name__ == '__main__': main()
实现格式化输出
brithday输出更正为输出为具体年龄,可视化更强
-
引入datetime模块
-
代码片段
def txl_dis(): '''从数据库中提取信息,然后打印出来 ''' status = True sql = 'select name,gender,brithday,tel from tb_txl' cursor.execute(sql) info = cursor.fetchall() if len(info) > 0: status = False print "name\tgender\tbrithday\ttel" print "------------------------------------" for name,gender,age,tel in info: today = datetime.date.today() age = (today-age).days/365 print "%(name)s\t%(gender)s\t%(age)s\t\t%(tel)s" % locals() if status: print print ">>> Empty,There is no user info in db <<<"
格式化之后的初始版本的脚本:
#!/usr/bin/env python #coding:utf8 #Author:zhuima #Date:2015-03-22 #Version:0.1 #Function:display a list and add date # 导入模块 import os import datetime #确保自定义模块能够被正常导入 import sys module_path = '/zhuima' sys.path.append(module_path) # 导入自定义模块 from db_config import conn,cursor def menu(): '''设置munu目录,提供给用户的操作接口 ''' print ''' 1.add user info 2.disp all user info 3.update user info by username 4:del user by username 5:check user info by username 0.exit program ''' op = raw_input('Please select one >>> ') return op def txl_add(): '''读取用户输入信息,并写入数据库''' name = raw_input('Please enput your name: ') gender = raw_input('Please enput your gender: ') brithday = raw_input('like (YYYY-MM-DD) >>> ') tel = raw_input('Please enput your tel: ') sql = 'insert into tb_txl values (null,%s,%s,%s,%s)' cursor.execute(sql,(name,gender,brithday,tel)) conn.commit() def txl_dis(name=None): '''从数据库中提取信息,然后打印出来 ''' status = True sql = 'select name,gender,brithday,tel from tb_txl' cursor.execute(sql) info = cursor.fetchall() if len(info) > 0: status = False print "name\tgender\tage\ttel" print "------------------------------------" for name,gender,age,tel in info: today = datetime.date.today() age = (today-age).days/365 print "%(name)s\t%(gender)s\t%(age)s\t%(tel)s" % locals() if status: print print ">>> Empty,There is no user info in db <<<" #print info def txl_del(): status = True name = raw_input('Delete Information By Name >>> ') select_sql = 'select name from tb_txl' cursor.execute(select_sql) info = cursor.fetchall() for line in info: if name in line: status = False delete_sql = 'delete from tb_txl where name=%s' cursor.execute(delete_sql,(name,)) conn.commit() if status: print print ">>>Unkonw User,Please Try again! <<<" def txl_update(): statue = True name = raw_input('Update Information By Name >>> ') select_sql = 'select name from tb_txl' cursor.execute(select_sql) info = cursor.fetchall() for line in info: if name in line: status = False gender = raw_input('Update Your Gender for %s >>> ' % name) brithday = raw_input('Update Your Brithday like (YYYY-MM-DD) for %s >>> ' % name) tel = raw_input('Update Your Tel for %s >>> '% name) update_sql = 'update tb_txl set gender=%s,brithday=%s,tel=%s where name=%s' cursor.execute(update_sql,(gender,brithday,tel,name,)) conn.commit() if status: print print ">>>Unkonw User,Please Try again! <<<" def txl_check(): status = True name = raw_input('Enter The name >>> ') sql = 'select name,gender,brithday,tel from tb_txl where name = %s' cursor.execute(sql,(name,)) info = cursor.fetchall() if len(info) > 0: status = False print "name\tgender\tbrithday\ttel" print "------------------------------------" for name,gender,age,tel in info: today = datetime.date.today() age = (today-age).days/365 print "%(name)s\t%(gender)s\t%(age)s\t%(tel)s" % locals() if status: print print ">>> Empty,There is no user info in db <<<" def txl_exit(): ''' 退出程序 ''' cursor.close() conn.close() os._exit(0) def txl_error(): ''' 当用户输出选项不在定义的选项内的时候,报错''' print print 'Unkonw options,Please try again!' def main(): '''主程序 ''' # 定义dict,配合函数实现switch功能 ops = { '1':txl_add, '2':txl_dis, '3':txl_update, '4':txl_del, '5':txl_check, '0':txl_exit, } while True: op = menu() ops.get(op,txl_error)() if __name__ == '__main__': main()
脚本中存在着很多重复代码以及bug,仅作参考,如果哪位想要调试可以进行下载重新更改
本文转自lovelace521 51CTO博客,原文链接:http://blog.51cto.com/lovelace/1631831,如需转载请自行联系原作者