Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert values in mysql from loop in Python [duplicate]

Tags:

python

mysql

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

like image 953
DaniKR Avatar asked Jun 30 '15 13:06

DaniKR


2 Answers

You did not commit your transaction. Try adding db.commit() after the loop.

like image 162
Nebril Avatar answered Oct 06 '22 01:10

Nebril


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

like image 45
Richard Avatar answered Oct 06 '22 00:10

Richard