本文重点在于演示Python对SQLite数据库的操作,以及命令行式菜单的工作原理和实现。

首先使用SQLite Database Browser创建SQLite数据库data.db,然后创建一个数据表addressList,最后在数据表addressList中创建字段id(INTEGER PRIMARY KEY类型)、name(TEXT类型)、sex(TEXT类型)、age(NUMERIC类型)、department(TEXT类型)、telephone(TEXT类型)和qq(TEXT类型)。然后编写下面的程序,运行后根据不同的命令进入查看、删除、增加等不同的功能或退出程序。

import sqlite3

def menu():
    '''本函数用来显示主菜单'''
   
    usage = ('\tL/l: List all the information.',
             '\tD/d: Delete the information of certain people.',
             '\tA/a: Add new information for a new people',
             '\tQ/q: Exit the system.',
             '\tH/h: Help, view all commands.')
    print('Main menu'.center(70, '='))
    for u in usage:
        print(u)

def doSql(sql):
    '''用来执行SQL语句,尤其是INSERT和DELETE语句'''
   
    conn = sqlite3.connect('data.db')
    cur = conn.cursor()
    cur.execute(sql)
    conn.commit()
    conn.close()
   
def add():
    '''本函数用来接收用户输入,检查格式,然后插入数据库'''
   
    print('Add records'.center(70, '='))
   
    #获取输入,只接受正确格式的数据
    while True:
        record = input('Please input name, sex, age, department, telephone, qq(Q/q to return):\n')
        #输入q或Q表示退出,结束插入记录的过程,返回主菜单
        if record in ('q', 'Q'):
            print('\tYou have stopped adding record.')           
            return
       
        #正确的格式应该恰好包含5个英文逗号
        if record.count(',') != 5:
            print('\tformat or data error.')
            continue
        else:
            name, sex, age, department, telephone, qq = record.split(',')
            #性别必须是F或M
            if sex not in ('F', 'M'):
                print('\tsex must be F or M.')
                continue
            #手机号和qq必须是数字字符串
            if (not telephone.isdigit()) or (not qq.isdigit()):
                print('\ttelephone and qq must be integers.')
                continue
           
            #年龄必须是介于1到130之间的整数
            try:
                age = int(age)
                if not 1<=age<=130:
                    print('\tage must be between 1 and 130.')
                    continue
            except:
                print('\tage must be an integer.')
                continue
           
        sql = 'INSERT INTO addressList(name,sex,age,department,telephone,qq) VALUES("'
        sql = sql + name + '","' + sex + '",' + str(age) + ',"' + department + '","'
        sql = sql + telephone + '","' + qq + '")'
        doSql(sql)
        print('\tYou have add a record.')

def exist(recordId):
    '''本函数用来测试数据表中是否存在recordId的id'''
   
    conn = sqlite3.connect('data.db')
    cur = conn.cursor()
    cur.execute('SELECT COUNT(id) from addressList where id=' + str(recordId))
    c = cur.fetchone()[0]
    conn.close()
    return c!=0

def remove():
    '''本函数用来接收用户输入的id号,并删除数据库中该id对应的记录'''
   
    print('Delete records'.center(70, '='))
   
    while True:
        #输入q或Q,返回上一级目录
        x = input('Please input the ID to delete(Q/q to return):\n')
        if x in ('q', 'Q'):
            print('\tYou have stopped removing record.')
            return

#要删除的id必须是数字,并且已存在于数据库中
        try:
            recordId = int(x)
            if not exist(recordId):
                print('\tThis id does not exists.')
            else:
                sql = 'DELETE FROM addressList where id=' + x
                doSql(sql)
                print('\tYou have deleted a record.')
        except:
            print('\tid must be an integer')
           
def listInformation():
    '''本函数用来查看所有记录'''
   
    sql = 'SELECT * FROM addressList ORDER BY id ASC'
    conn = sqlite3.connect('data.db')
    cur = conn.cursor()
    cur.execute(sql)
    result = cur.fetchall()
    if not result:
        print('\tDatabase has no record at this time.')
    else:
        #格式化输出所有记录
        print('All records'.center(70, '='))
        print('Id    Name    Sex    Age    Department        Telephone    QQ')
        for record in result:
            print(str(record[0]).ljust(6), end='')
            print(record[1].ljust(8), end='')
            print(record[2].ljust(7), end='')
            print(str(record[3]).ljust(7), end='')
            print(record[4].ljust(18), end='')
            print(record[5].ljust(13), end='')
            print(record[6])
        print('='*30)
    conn.close()
   
def main():
    '''系统主函数'''
   
    print('Welcome to the addresslist manage system.')
    menu()
    while True:
        command = input('Please choose a command:')
        if command in ('L', 'l'):
            listInformation()
        elif command in ('D', 'd'):
            remove()
            menu()
        elif command in ('A', 'a'):
            add()
            menu()
        elif command in ('Q', 'q'):
            break
        elif command in ('H', 'h'):
            menu()
        else:
            print('\tYou have input a wrong command.')

#调用主函数,启动系统
main()

Python+SQLite开发无界面版通信录管理系统相关推荐

  1. tkinter GUI版通信录管理系统

    tkinter GUI版通信录管理系统 实验要求 设计一个GUI版的通信录,连接data.db数据库(数据库在QQ群文件中),把数据库里的通信录记录读取出来,在窗口上放置用来显示通信录信息的表格,使用 ...

  2. 微课|中学生可以这样学Python(例11.3):tkinter通信录管理系统4

    适用教材: 董付国,应根球.<中学生可以这样学Python>.清华大学出版社,2017. 第11章  综合案例设计与分析 例11.3  tkinter版通信录管理系统 京东购买链接:htt ...

  3. 微课|中学生可以这样学Python(例11.3):tkinter通信录管理系统1

    适用教材: 董付国,应根球.<中学生可以这样学Python>.清华大学出版社,2017. 第11章  综合案例设计与分析 例11.3  tkinter版通信录管理系统 京东购买链接:htt ...

  4. 微课|中学生可以这样学Python(例11.3):tkinter通信录管理系统2

    适用教材: 董付国,应根球.<中学生可以这样学Python>.清华大学出版社,2017. 第11章  综合案例设计与分析 例11.3  tkinter版通信录管理系统 京东购买链接:htt ...

  5. 微课|中学生可以这样学Python(例11.3):tkinter通信录管理系统3

    适用教材: 董付国,应根球.<中学生可以这样学Python>.清华大学出版社,2017. 第11章  综合案例设计与分析 例11.3  tkinter版通信录管理系统 京东购买链接:htt ...

  6. 微课|中学生可以这样学Python(例9.2):无界面通信录管理系统

    适用教材: 董付国,应根球.<中学生可以这样学Python>.清华大学出版社,2017. 第9章  SQLite数据库编程基础 例9.2  无界面通信录管理系统 京东购买链接:https: ...

  7. c语言学生成员管理代码报告怎么写,C语言学生通信录管理系统课程设计报告

    <C语言学生通信录管理系统课程设计报告>由会员分享,可在线阅读,更多相关<C语言学生通信录管理系统课程设计报告(18页珍藏版)>请在人人文库网上搜索. 1.实验名称 :学生通信 ...

  8. Python编写无界面版打字练习程序

    开学第一课:一定不要这样问老师Python问题 在线开放课程"Python程序设计基础"第7次开课通知 智慧树大学共享课"Python数据分析与数据可视化"20 ...

  9. python爬虫之无界面模式操作/scrapy框架

    文章目录 前情回顾 cookie模拟登陆 三个池子 selenium+phantomjs/chrome/firefox 今日笔记 chromedriver设置无界面模式 selenium - 键盘操作 ...

最新文章

  1. 驴友生涯的开始--香八拉路线精选
  2. 虚拟机实现二层交换机_局域网SDN技术硬核内幕 5 虚拟化网络的实现
  3. windows driver 分配内存
  4. python编程词汇-基本 Python 词汇
  5. oracle 提取首字母,oracle 取字段文字拼音首字母
  6. 手机定位和什么有关?关机后的手机还能被定位吗?
  7. 95-230-010-源码-WordCount走读-概述
  8. arcgis不闭合线转面_地理工具学习--arcgis篇(15):CAD和SHP的简单转换
  9. Spring Cloud Eureka 源码分析(一) 服务端启动过程
  10. MVCC(Multiversion concurrency control)
  11. OldSkoolVerb Plus for Mac(算法混响插件)
  12. 大学计算机协会大一面试,大一学生社团面试自我介绍
  13. php 启用ereg,PHP 5.3的ereg / eregi替换
  14. Vmware 虚拟机克隆后网卡地址的修改
  15. 为什么有人愿意将软件开源和共享?
  16. 法国队夺了世界杯冠军,却彻底打了AI预测的脸
  17. PLC模拟量数据的处理
  18. 斗鱼直播Android开发二面被刷,好文推荐
  19. USBASP烧录出现的几种错误
  20. COD去除常见的工艺,离子交换树脂除COD

热门文章

  1. curl php 禁用ip6,CentOS 6禁用IPv6解决curl Couldn’t resolve host或dns解析慢
  2. excel 切片器 html,excel切片器怎么使用2010
  3. 正则翻译工具_PythonBasics 中文系列教程 · 翻译完成
  4. java工具类使用_Java工具类使用注意事项
  5. springcloud整合php,详细讲解springcloud的组件之RestTemplate集成的Ribbbon
  6. jsp java 交互_JSP-Servlet入门4之JSP数据交互
  7. 从ASM拷贝文件的方法
  8. html5的新特性都有什么,html5的新特性
  9. linux内核killler,Linux内核参数overcommit_memory和OOM killer介绍
  10. 基于JAVA+SpringMVC+Mybatis+MYSQL的甜品店商城