这个例子创建了一个简单的表, 表的内容为姓名和年龄, 实现了增、删、改、查的基本功能。
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()