I have a python script that makes about ten INSERTs into a MySQL database. This is its current structure:
conn = MySQLdb.connect (host = DB_HOST,
port = DB_PORT,
user = DB_USER,
passwd = DB_PASSWORD,
db = DB_NAME)
cursor = conn.cursor()
cursor.execute("INSERT INTO...")
# do some stuff, then another INSERT
cursor.execute("INSERT INTO...")
# do some other stuff, then another INSERT
cursor.execute("INSERT INTO...")
etc...
conn.commit()
cursor.close()
conn.close()
Is the above the correct way to do multiple inserts, or should I be closing the cursor after each INSERT? Should I be doing a commit after each INSERT?
It doesn’t much matter. Cursors are reused cleverly.
You can close them to be super careful of your resources.
Do this.
This assures that the cursor is closed no matter what kind of exceptions happen.
That depends on what your application is expected to do.
If it’s an “all or nothing” proposition, then you do one commit. All the inserts are good or none of them are.
If partial results are acceptable, then you can commit after each insert.