Python如何知道记录是否成功插入

标签 python mysql mysql-connector

我正在使用 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/

相关文章:

当正则表达式匹配时,Python 的 Re.Sub 不改变任何内容

php - MYSQL不等于'<>'不起作用。怎么解决呢?

c# - 字段列表中的未知列 - MySQL 更改后

c# - 使用 C# MySQL 连接器进行批量更新的最快、最有效的方法是什么?

mysql - 在 MySql 中,如何根据特定的 related_id 可用的记录 id 创建一组连续的值

python - mysqlconnector python错误: "Commands out of sync; you can' t run this command now"

python - 将 python 程序设置为 SCHED_RR 或 SCHED_FIFO

python - 代码块中的 Sphinx 变量替换

python - 在列表中查找数字递增(具有不同增量)的组

MySQL PXC Gcache 计算