这是我的代码。我只想更新书名和作者姓名,并且希望其他参数值保持不变。我收到如下错误。不更改参数应该怎么办?我试图仅将变量名传递为year和isbn,但是它没有用。我在类似的问题中搜索了很多,但没有帮助。
def update(id, title, author, year, isbn):
conn = psycopg2.connect("dbname='' user= password='' host='localhost' port='5432' ")
cur = conn.cursor()
cur.execute("UPDATE dnr SET title=%s, author=%s, year=%s, isbn=%s WHERE id=%s", (title, author, year, isbn, id))
conn.commit()
conn.close
update(1, "The Sky", "Jonh Smith")
错误:
TypeError: update() missing 2 required positional arguments: 'year' and 'isbn'
您可以使用默认值作为可选参数,并检查它们是否已设置,从而一致地调整查询和数据。
def update(id, title, author, year=None, isbn=None):
conn = psycopg2.connect("dbname='' user= password='' host='localhost' port='5432' ")
cur = conn.cursor()
query = "UPDATE dnr SET title=%s, author=%s"
data = [title, author]
if year is not None:
query += ", year=%s"
data.append(year)
if isbn is not None:
query += ", isbn=%s"
data.append(isbn)
query += " WHERE id=%s"
data.append(id)
cur.execute(query, data)
conn.commit()
conn.close
update(1, "The Sky", "Jonh Smith")