Skip to content

How to insert values in mysql from loop in Python

An answer to this question on Stack Overflow.

Question

In MySQL I have create db with name "test" and one table with name "table". Table have one column name: "A" and set as datatype INT(1).

In Python I have this code:

import MySQLdb
db = MySQLdb.connect(host="localhost",
				 user="root",
				 db="test")
cur = db.cursor()
myList = [1,2,3,4]
for row in myList:
   print row
   cur.execute("INSERT INTO table (a) VALUES (%s)" % row)

Goal from code above is after loop is finish my table "table" shoud have data like this:

|A|
|1|
|2|
|3|
|4|

But my table is empty after refresing. So my question is how to insert into table from loop in Python

Tnx

Answer

You can use db.commit () after your data is loaded or set db.autocommit(True) beforehand.