Gia Duong Duc Minh Gia Duong Duc Minh - 1 year ago 71
MySQL Question

Python how to know if a record inserted successfully or not

I'm using Python MySQL Connector, I inserted a record into database, and it was successful. But in Python code, how can I know if it is inserted or not?
My Table does not have a primary key.

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))
except :
return result

Answer Source

You can use .rowcount attribute:

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]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download