python 中的 SQLite - 每次插入后打印

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)

这只打印所有新插入的记录一次。我希望能够在每次插入后打印。

第一次插入后:

1 首新

第二次插入后:

1 首新

2秒新建

您必须使用 execute() 而不是 executemany() 一次插入一行,并且在插入每一行之后您必须执行 SELECT... 语句:

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)

请注意,如果 table 中已经有包含 type = 'New' 的行,它们将全部由 SELECT... 语句返回。