import sqlite3
def opendb():
conn=sqlite3.connect("mydb.db")
cur=conn.execute("create table if not exists tongxunlu(usernum integer primary key,username varchar(128),address varchar(125),telnum varchar(128))")
return cur,conn
def show_all_db():
print("--------------------处理后的数据--------------------")
hel=opendb()
cur=hel[1].cursor()
cur.execute("select * from tongxunlu")
res=cur.fetchall()
for line in res:
print(line)
cur.close()
def input_info():
usernum=input("请输入学号:")
username1=input("请输入姓名:")
address1=input("请输入地址:")
telnum1=input("请输入联系电话:")
return usernum,username1,address1,telnum1
def add_to_db():
print("--------------------欢迎使用添加数据功能--------------------")
person=input_info()
hel=opendb()
hel[1].execute("insert into tongxunlu (usernum,username,address,telnum) values (?,?,?,?)",(person[0],person[1],person[2],person[3]))
hel[1].commit()
print("--------------------数据添加成功!--------------------")
show_all_db()
hel[1].close()
def del_db():
print("--------------------欢迎使用删除数据功能--------------------")
del_choice=input("请输入想要删除的学号")
hel=opendb()#返回游标conn
hel[1].excute("delete from tongxunlu where usernum ="+del_choice)
hel[1].commint()
print("--------------------数据删除成功!--------------------")
show_all_db()
hel[1].close
def alter_db():
print("--------------------欢迎使用修改数据功能--------------------")
alter_choice=input("请输入想要修改学生的学号")
hel=opendb()
person=input_info()
hel[1].execute("update tongxunlu set usernum=?,username=?,address=?,telnum=? where usernum = "+alter_choice,(person[0],person[1],person[2],person[3]))
hel[1].commint()
show_all_db()
hel[1].close()
def search_db():
print("--------------------欢迎使用查询数据功能--------------------")
search_choice=input("请输入要查询学生的学号")
hel=opendb()
cur=hel[1].cursor()
cur.execute("select * from tongxunlu where usernum = "+search_choice)
hel[1].commit()
print("--------------------你所查找的数据如下--------------------")
res=cur.fetchall()
for line in res:
print(line)
cur.close()
hel[1].close()
def del_table():
hel=opendb()
cur=hel[1].cursor()
cur.execute("drop table tongxunlu")
show_all_db()
if __name__=="__main__":
flag=1
while flag==1:
print("--------------------欢迎使用数据库通讯录--------------------")
choiceshow="""
请选择您的进一步操作:
(添加) ---A
(删除) ---B
(修改) ---C
(查询) ---D
(查看现有数据)---E
(删除整个表) ---F
"""
choice=input(choiceshow)
if choice=="A":
add_to_db()
flag=int(input("是否继续(0 or 1)?"))
elif choice=='B':
del_db()
flag=int(input("是否继续(0 or 1)?"))
elif choice=='C':
alter_db()
flag=int(input("是否继续(0 or 1)?"))
elif choice=='D':
search_db()
flag=int(input("是否继续(0 or 1)?"))
elif choice=='E':
show_all_db()
flag=int(input("是否继续(0 or 1)?"))
elif choice=='F':
del_table()
flag=int(input("是否继续(0 or 1)?"))
else:
print("输入错误!请输入:A|B|C|D|E|F")
首先建立数据库链接conn,然后建立游标cur,利用游标cur的execute语句进行各种操作,提交并关闭。