Search code examples
sqlpython-3.xdatabasesqliteexecute

Sqlite in python - print after every insert


con=sqlite3.connect('database')
cursor=con.cursor()
sql=[("1", "first", "New"),("2", "second", "New"),("3", "third", "New")]
cursor.executemany("""insert into table(srnumber, order, type)
              values(?,?,?)""",sql)
for row in cursor.execute('select * from table WHERE type ="New"'):
    print(row)

This prints all the newly inserted records only once. I want to be able to print after every insert.

After the first insert:

1 first New

After the second insert:

1 first New

2 second New


Solution

  • You must insert the rows one at a time with execute() and not executemany() and after each row is inserted you must execute the SELECT... statement:

    rows = [("1", "first", "New"),("2", "second", "New"),("3", "third", "New")]
    sql_insert = "INSERT INTO tablename(srnumber, `order`, type) VALUES (?, ?, ?)"
    sql_select = "SELECT * FROM tablename WHERE type = 'New'"
    for row in rows:
        cursor.execute(sql_insert, row)
        for inserted_row in cursor.execute(sql_select):
            print(inserted_row)
    

    Note that if there are already rows in the table with type = 'New' they will all be returned by the SELECT... statement.