1

I am writing my first python script, and I am trying to connect it to a mysql db to insert rows.

import MySQLdb

db = MySQLdb.connect("localhost","root","xxx","pytest" )

cursor = db.cursor()

cursor.execute("INSERT INTO `first_table` (`name`) VALUES ('boop') ")

When I check the mysql db via phpmyadmin, it contains no rows, however if the auto incrementing ID was 5 and then I run the script 2 times, when I insert a new row it inserts it as id= 8 so the script has been incrementing the primary key but not inserting the rows?

The script reports no mysql errors, so I'm a bit lost here.

Melbourne2991
  • 11,707
  • 12
  • 44
  • 82

3 Answers3

2

In yuor case please use

import MySQLdb

    db = MySQLdb.connect("localhost","root","jimmypq79","pytest" )
    cursor = db.cursor()
    cursor.execute("INSERT INTO `first_table` (`name`) VALUES ('boop') ")
    db.commit()

Please put this in top of the code like this--

db = MySQLdb.connect("localhost","root","jimmypq79","pytest" )
db.autocommit(True)

check here

Community
  • 1
  • 1
Nisarg
  • 3,024
  • 5
  • 32
  • 54
1

You can use

 cursor.autocommit(True)

in the beginning of the code for automatically committing the changes .

tusharmakkar08
  • 706
  • 1
  • 12
  • 32
1

you use,

  db.commit()

after insert query

Marsh
  • 173
  • 1
  • 14