我正在尝试使用 psycopg2 游标更新在 ElephantSQL 服务上运行的 PostgreSQL 表。从我的计算机 (MacOS) 执行 SQL 语句。该脚本认为一切正常,但表未更新。我已经指定了“connection.autocommit=True”并且还在 cursor.execute(SQL) 语句之后包含了“connection.commit()”语句。什么都不管用。帮助将不胜感激。
这是一个代码片段:
# Establish Connection
try:
connection = psycopg2.connect(conn_string)
connection.autocommit=True
except Exception as e:
print("******Cannot connect to DB****** \n" + "error: " + str(e))
exit()
# --- Later on, when trying to update the DB
if request.method == "POST":
if form.validate_on_submit():
username_to_delete = request.form['username']
print(" username to delete is: " + username_to_delete)
try:
with connection, connection.cursor() as cursor:
cursor.execute("DELETE FROM users WHERE username='username_to_delete';")
connection.commit()
cursor.close()
except Exception as e:
flash("Delete operation failed, error: " + str(e))
print("Delete operation failed, try again ..." + str(e))
return render_template("delete_user.html", form=form)
flash("User Deleted Successfully!!")
username_to_delete = ""
return render_template("delete_user.html", form=form)
else:
print(" Error with Delete Form validation")
flash(" There was a problem deleting user, try again...")
return render_template("delete_user.html", form=form)
else:
flash(" User Delete failed! - form problems")
return render_template("delete_user.html", form=form)
正如我提到的,脚本报告用户已成功删除,但事实并非如此。
正如我所说,我整天都在为此挠头。希望有人能指出我正确的方向。
我尝试将自动提交属性添加到连接中,并且还在事务之后添加了 connection.commit() 语句。不知何故,这对我不起作用。非常感谢您的帮助。
问题的答案与 DB commit() 或 autocommit=True 无关。
正如评论所指出的,我错误地传递了所需的参数。
cursor.execute 语句不正确,因为没有将元组作为语句的第二部分传递。
try:
with connection, connection.cursor() as cursor:
cursor.execute("DELETE FROM users WHERE id=%s;",(id_to_delete,))
connection.commit()
cursor.close()
except Exception as e:
flash("Delete operation failed, error: " + str(e))
print("Delete operation failed, try again ..." + str(e))
return render_template("delete_user.html", form=form)
所以语句应该是:cursor.execute("SELECT id FROM users WHERE username=%s;", (username,)) 。最后一部分:(用户名,)之前没有正确完成。感谢 Richard Hutton 和 Adrian Klaver。您的意见帮助我解决了这个问题。