Search code examples
pythonsqliteinsertrowcount

Number of rows inserted into SQLite db is negative


I'm trying to insert new records into SQLite database from Python code.

  con = sqlite.connect(connectionString)
  cur = con.cursor()
  countOfNewItems = 0
  for ...
    try:
      con.execute("insert or ignore into items ...")
      countOfNewItems += cur.rowcount
    except:
      cur.close()
      con.close()
      print "Error when inserting item '%s' to database." % item
      exit(1)
  cur.close()
  con.commit()
  con.close()
  print "%d new items have been inserted." % countOfNewItems

My code reports negative number of inserted records (-5141).

Because my database was empty, I could find out how many records were inserted via command line

select count(*) from items;

4866

Could you advise me what's wrong. Why the two values don't match and why it's negative?


Solution

  • Try cur.execute instead of con.execute. cur.rowcount then returns 1 for me for a simple insert.