Entering data in mysql, commit () does not work

2

I wanted to insert into the Database definitely. But with this code I am not succeeding, the registry is saved but does not commit() :

import MySQLdb

def conn():
  try:
    db = MySQLdb.connect(host="127.0.0.1",user="root",passwd="",db="yoo")
    return db
  except:
    exit("sorry can't connect")

def insert(cur, names):
  try:
    for i in names:
      cur.execute("INSERT INTO test (person) VALUES (%s)", str(i))
    conn().commit() #write up in DB definitly
    return "success"
  except:
    return "Something went wrong with the insertion"

def main():
  conn()
  cur = conn().cursor()

  numOfNames = int(raw_input("how many names?\n"))
  names = []

  for i in range(numOfNames):
    name = raw_input("Insert a name\n")
    names.append(name)

  print insert(cur, names)

main()
    
asked by anonymous 04.03.2015 / 11:33

1 answer

1

I believe it is because the reference of the variable being treated is lost, so try to see if

import MySQLdb

def conn():
  try:
    db = MySQLdb.connect(host="127.0.0.1",user="root",passwd="",db="yoo")
    return db
  except:
    exit("sorry can't connect")

def insert(db, names):
  try:
    for i in names:
      db.cursor().execute("INSERT INTO test (person) VALUES (%s)", str(i))
    db.commit() #write up in DB definitly
    return "success"
  except:
    return "Something went wrong with the insertion"

def main():
  db = conn()

  numOfNames = int(raw_input("how many names?\n"))
  names = []

  for i in range(numOfNames):
    name = raw_input("Insert a name\n")
    names.append(name)

  print insert(db, names)

main()
    
04.03.2015 / 12:34