我试图通过用户输入来管理联系人列表。程序会询问用户想要做什么,要么添加新联系人,编辑联系人,删除联系人或显示联系人列表,如果用户想要编辑联系人,那么他会询问联系人的ID他想改变,然后他想改变的行(姓名,姓氏或号码)..我不知道的是,我如何使用sql UPDATE命令和用户提供的id,然后我如何使用新名称,或用户使用相同命令给出的姓氏或号码,更新?因此,用户实际上可以从菜单中选择要编辑的联系人以及要编辑的参数。
这是我的代码。
import sqlite3
asd = True
while asd:
conn = sqlite3.connect('contactsdb.db')
c = conn.cursor()
c.execute('''DROP TABLE IF EXISTS contacts''')
c.execute('''CREATE TABLE contacts
(id INTEGER PRIMARY KEY, Nombre TEXT, Apellido TEXT, Numero de celular INTEGER)''')
# def agregarconbg():
# global nombre
# global apellido
# global numero
def agregarcon():
nombre = input("Add name")
apellido = input("Add lastname")
numero = input("Add number")
# c = conn.cursor()
c.execute("INSERT INTO contacts (nombre, apellido, numero) VALUES(?,?,?);",(nombre,apellido,numero))
conn.commit()
def editnom():
nuevonom = input("Add new name")
###################################################
###################################################
#########What do i do around here?!################
c.execute("UPDATE contacts set nombre where ID=1",(nuevonom))
conn.commit
# def editap():
#
# def editnum():
def editarcon():
print ("What id do you want to change?")
cambiar = input("Introduce the id you want to change:")
print("""What do you want to change
1 - Name
2 - Lastname
3 - Number""")
cambiarpar = int(input("Seleccion:"))
if cambiarpar == 1:
editnom()
elif cambiarpar == 2:
editap()
elif cambiarpar == 3:
editnum()
else:
print("Wrong INPUT")
# c = conn.cursor()
#def borrarcon():
# c = conn.cursor()
def printsql():
# c = conn.cursor()
c.execute('SELECT * FROM contacts ORDER BY id')
listT = ["ID","Nombre:","Apellido:","Numero:"]
k = 0
for i in c:
print("\n")
for j in i:
print (listT[k])
print(j)
if k < 3: k+=1
else: k = 0
conn.commit()
print('Agenda de contactos')
print('''Que deseas hacer?
1 - Add a contact
2 - Edit a contact
3 - Delete a contact
4 - Show contacts''')
seleccion = int(input("Seleccion:"))
if seleccion == 1:
agregarcon()
elif seleccion == 2:
editarcon()
conn.commit()
elif seleccion == 3:
borrarcon()
conn.commit
elif seleccion == 4:
printsql()
答案 0 :(得分:0)
将Cambiar(ID)作为参数传递给editnom()并将其用作更新语句的一部分,再使用nombre = variable实际更新记录
See this page for SQLite3 UPDATE
See this for how to pass variables through to functions in Python
def editnom(cambiar):
nuevonom = input("Add new name")
###################################################
###################################################
#########What do i do around here?!################
c.execute("UPDATE contacts set nombre = ? where ID=?",(nuevonom,cambiar))
conn.commit
if cambiarpar == 1:
editnom(cambiar)