[py]python寫一個通信錄step by step V3.0

python寫一個通信錄step by step V3.0

參考: http://blog.51cto.com/lovelace/1631831python

更新功能:mysql

  • 數據庫進行數據存入和讀取操做
  • 字典配合函數調用實現switch功能
  • 其餘:函數、字典、模塊調用

注意問題:sql

  • 一、更優美的格式化輸出
  • 二、把日期換算成年齡
  • 三、更新操做作的更優雅

準備工做
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    |                |
+----------+----------+------+-----+---------+----------------+

一、模板準備

相對於V一、V二、V3版本的,模板基本一致
模板app

#!/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()

二、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()

三、鏈接數據庫,實現增,查功能

導入db_config模塊中的conn和cursor,而後直接使用
代碼片斷測試

確保自定義模塊可以被正常導入fetch

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才行)ui

[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

四、鏈接數據庫,實現刪功能

導入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

五、鏈接數據庫,實現更新功能

根據用戶名搜索相關的值來進行更新
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! <<<

六、鏈接數據庫,實現檢索功能

根據用戶名搜索相關的值而後返顯結果
代碼片斷

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,僅做參考,若是哪位想要調試能夠進行下載從新更改

v1.0 v2.0版本

python寫一個通信錄step by step V1.0
python寫一個通信錄step by step V2.0

相關文章
相關標籤/搜索