Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL data being lost after getting inserted successfully with Python mysql.connector

I'm using python mysql.connector for some database operation. My database table structure is like this:

enter image description here

I running a python script with Faker Package(fake-factory 0.5.0) to populate this database table. After insertion I run a query to verify that data is properly stored into the table. The python script shows all inserted data and finishes with exit code 0

But when I explore that table through phpMyadmin it doesn't show those inserted rows. These inserted data doesn't persist in after the next run yet.

Here is my code:

import mysql.connector
from faker import Faker

fake = Faker()

cnx = mysql.connector.connect(user='root', password='001',
                              host='127.0.0.1',
                              database='smf')
cursor = cnx.cursor()

for i in range(1, 5):
    query = "insert into user " + "(userid, name) values("+ str(i) + ", '" + fake.name() + "')"
    cursor.execute(query)

query = "select * from user"
cursor.execute(query)

for (x) in cursor:
    print ("name = " + format(x))

cnx.close()
like image 350
Mostafiz Rahman Avatar asked Aug 30 '26 00:08

Mostafiz Rahman


1 Answers

By default Connector/Python turns autocommit off, and MySQL 5.5 and later uses transactional InnoDB tables, so it is necessary to commit your changes using the connection's commit() method. You could also roll back using the rollback() method.

So, putting cnx.commit() command after cursor.execute(query) solves your problem.

like image 145
madMDT Avatar answered Aug 31 '26 14:08

madMDT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!