Insert data into mysql, commit() does not work

Asked

Viewed 552 times

3

I wanted to enter in the database definitely. But with this code I am not able, the record 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()
  • 1

    it wouldn’t have to be cur.commit()?

  • According to http://stackoverflow.com/questions/5687718/how-can-i-insert-data-into-a-mysql-database, I don’t think so

  • humm. It doesn’t work either. But why would I miss the reference?

1 answer

2


I believe that it is because it is lost the reference of the variable being treated, try so ve se da

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()
  • Very obnoxious, it worked, I hadn’t gotten there. I don’t understand why you miss the reference, but this was a good way around it

  • pq every time you call Conn() it opens a new connection and every connection has its cursor, you create a cursor in a connection and create another connection to commit but on its cursor it has nothing

  • Haa... OK I get it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.