我正在使用 Python MySQL 连接器,我在数据库中插入了一条记录,并且成功。但是在 Python 代码中,我怎么知道它是否被插入呢? 我的表没有主键。
def insert(params) :
db_connection = Model.get_db_connection()
cursor = db_connection.cursor()
try :
cursor.execute("""INSERT INTO `User`(`UID`, `IP`) VALUES(%s,%s);""", (params))
db_connection.commit()
except :
db_connection.rollback()
Model.close_db(db_connection)
return result
最佳答案
您可以使用 .rowcount
属性:
cursor.execute("""INSERT INTO `User`(`UID`, `IP`) VALUES(%s,%s);""", params)
print("affected rows = {}".format(cursor.rowcount))
.rowcount This read-only attribute specifies the number of rows that the last .execute*() produced (for DQL statements like SELECT) or affected (for DML statements like UPDATE or INSERT). [9]
关于Python如何知道记录是否成功插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19046202/