Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to know if a record inserted successfully or not

Tags:

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))         db_connection.commit()     except :         db_connection.rollback()     Model.close_db(db_connection)     return result 
like image 341
Gia Duong Duc Minh Avatar asked Sep 27 '13 08:09

Gia Duong Duc Minh


People also ask

How do you know if a DB connection is successful in Python?

The connect() function establishes a connection to the python_mysql database and returns a MySQLConnection object. Third, check if the connection to the MySQL database has been established successfully by using is_connected() method.

How do I get the last inserted record in Python?

To get and print the ID of the last inserted row, lastrowid is used. This is a special keyword which is used to get the ID of the last inserted row. There are certain prerequisites to be taken care of before using this method. The ID column must be the primary key in the table.


1 Answers

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]

like image 199
falsetru Avatar answered Oct 01 '22 08:10

falsetru