首页 > 数据库 >Python+SQLite开发无界面版通信录管理系统

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

时间:2023-06-09 21:03:23浏览次数:45  
标签:qq SQLite Python TEXT age sex record print 通信录


本文重点在于演示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!=0def 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()

标签:qq,SQLite,Python,TEXT,age,sex,record,print,通信录
From: https://blog.51cto.com/u_9653244/6451087

相关文章

  • 妙用Python集合求解啤酒问题(携程2016笔试题)
    问题描述:一位酒商共有5桶葡萄酒和1桶啤酒,6个桶的容量分别为30升、32升、36升、38升、40升和62升,并且只卖整桶酒,不零卖。第一位顾客买走了2整桶葡萄酒,第二位顾客买走的葡萄酒是第一位顾客的2倍。那么,本来有多少升啤酒呢?解析:由于该酒商只卖整桶酒,简单分析几个桶的容量可知,第二位顾客......
  • Python两种方法求解登楼梯问题(京东2016笔试题)
    问题:假设一段楼梯共15个台阶,小明一步最多能上3个台阶,那么小明上这段楼梯一共有多少种方法?解析:从第15个台阶上往回看,有3种方法可以上来(从第14个台阶上一步迈1个台阶上来,从第13个台阶上一步迈2个台阶上来,从第12个台阶上一步迈3个台阶上来),同理,第14个、13个、12个台阶都可以这样推算,从......
  • 大数据分析python
    #导库importnumpyasnpimportpandasaspd#读取数据data=pd.read_csv('logistics.csv')data.head(10)思路:直接查看不同公司的数量即可df1=data.groupby('货运公司名称').size().reset_index(name='count')#直接对货运公司的名称做统计(示例:天天速递25)df12.接通知对......
  • 使用Python编写简易定时器
    简单模拟了定时器功能,需要的朋友可以自己改写和扩充功能。importdatetimeimportwinsoundimporttimeimportrandomdefTimer(y,m,d,h,mu,s):'''参数分别为年、月、日、时、分、秒'''stopTime=datetime.datetime(y,m,d,h,mu,s)maxTime=stopTime+......
  • 使用Python寻找黑洞数
     黑洞数是指这样的整数:由这个数字每位上的数字组成的最大数减去每位数字组成的最小数仍然得到这个数自身。例如3位黑洞数是495,因为954-459=495,4位数字是6174,因为7641-1467=6174。本文重点在于内置函数sorted()和reversed()的用法。defmain(n):'''参数n表示数字的位数,例如n=3......
  • Python中的具名元组类用法
    >>>fromcollectionsimportnamedtuple>>>Point=namedtuple('Point',['x','y','z'])#创建具名元组类>>>Point<class'__main__.Point'>>>>p=Point(3,4,5)#实例化对象......
  • Python“制作”midi音乐“两只老虎”
    从网上找了很多谱子,可惜没有音乐细胞看不太懂,根据自己的理解改了好几遍,还是听不出来“两只老虎”的感觉,于是在标题上加了双引号。这样的话就只能了解本文思路了,算是抛砖引玉吧,重点是Python标准库winsound的Beep()函数可以发出37到32767赫兹之间频率的声音,其第二个参数为发声时长。f......
  • Python标准库zlib提供的数据压缩功能
    Python标准库zlib中提供的compress()和decompress()函数可以用于数据的压缩和解压缩,在压缩数据之前需要先想办法编码为字节串。>>>importzlib>>>x='Python程序设计系列图书,董付国编著,清华大学出版社'.encode()>>>len(x)72>>>y=zlib.compress(x)>>>len(y)#对于重......
  • Python使用Queue对象实现多线程同步小案例
    queue模块的Queue对象实现了多生产者/多消费者队列,尤其适合需要在多个线程之间进行信息交换的场合,实现了多线程编程所需要的所有锁语义。Queue对象主要实现了put()和get()方法,分别用来往队列尾部追加元素和在队列头部获取并删除元素。这两个方法都允许指定超时时间,其用法分别为put(......
  • Python统计多个Powerpoint文件中幻灯片总数量
    晚上吃饭时突然想知道自己做了多少页《Python程序设计》系列教材的配套PPT,于是就有了下面的代码,这套PPT综合了《Python程序设计基础》(ISBN:9787302410584)、《Python程序设计(第2版)》(ISBN:9787302436515)和《Python可以这样学》(ISBN:9787302456469)以及将要出版的《Python程序设计开发宝典......