python使用sqlite3的例子

8 篇文章 0 订阅
3 篇文章 0 订阅

这个例子创建了一个简单的表, 表的内容为姓名和年龄, 实现了增、删、改、查的基本功能。

import sqlite3

class database:
    def __init__(self):
        self.conn = sqlite3.connect('test.db')
        print ("Opened database successfully")
        self.c = self.conn.cursor()
        self.choice = {'1': self.new_table, '2' : \
                                     self.add, '3': self.delete, \
                                     '4': self.change, '5': self.check}
    def __del__(self):
        self.conn.close()
    def new_table(self):
        name = input("please enter table's name\n")
        self.c.execute('''CREATE TABLE ''' +name+
    '''(NAME   CHAR(20)   NOT NULL,
            AGE    INT        NOT NULL);''')
        #名字不能有数字
        print("Table created successfully")
    def add(self):
        table_name = input("please input table's name\n")
        name = input("please input user's name\n")
        age = input("please input user's age\n")
        self.c.execute('''INSERT INTO '''+table_name+''' (NAME, AGE) VALUES ("'''+ name + '''", ''' + str(age) + ''');''');
    def delete(self):
        table_name = input("please input table's name\n") 
        name = input("please input the name you want to delete\n")
        self.c.execute("delete from " + table_name + ''' where name="''' + name+'''"''')
    def change(self):
        table_name = input("please input table's name\n") 
        name = input("please input your name\n")
        new_age = input("please enter the new age\n")
        self.c.execute("update " + table_name + " set AGE="+str(new_age) +''' where name="''' + name+'''"''')
    def check(self):
        table_name = input("please input table's name\n") 
        name = input("please input your name\n")
        result = self.c.execute("select age from " + table_name + ''' where name="''' + name+'''"''')
        for i in result:
            print("\nyour age is " + str(i[0]) + "\n")
    def loop(self):
        while(1):
            c = input("enter 1 to create a new table\nenter 2 to add information\n"\
                             +"enter 3 to delete information\nenter 4 to update information\n"\
                             +"enter 5 to check your age\n----------------------------------\n")
            self.choice.get(c)()
            self.conn.commit()

test = database()
test.loop()



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值