简体   繁体   English

Python SQLITE3 向后插入

[英]Python SQLITE3 Inserting Backwards

I have a small piece of code which inserts some data into a database.我有一小段代码将一些数据插入到数据库中。 However, the data is being inserting in a reverse order.但是,数据以相反的顺序插入。
If i "commit" after the for loop has run through, it inserts backwards, if i "commit" as part of the for loop, it inserts in the correct order, however it is much slower.如果我在 for 循环运行后“提交”,它会向后插入,如果我“提交”作为 for 循环的一部分,它会以正确的顺序插入,但速度要慢得多。
How can i commit after the for loop but still retain the correct order?如何在 for 循环之后提交但仍保留正确的顺序?

import subprocess, sqlite3
output4 = subprocess.Popen(['laZagne.exe', 'all'], stdout=subprocess.PIPE).communicate()[0]
lines4 = output4.splitlines()

conn = sqlite3.connect('DBNAME')
cur = conn.cursor()


for j in lines4:
    print j
    cur.execute('insert into Passwords (PassString) VALUES (?)',(j,))
conn.commit()
conn.close()

You can't rely on any ordering in SQL database tables.您不能依赖 SQL 数据库表中的任何顺序。 Insertion takes place in an implementation-dependent manner, and where rows end up depends entirely on the storage implementation used and the data that is already there.插入以依赖于实现的方式发生,行的最终位置完全取决于使用的存储实现和已经存在的数据。

As such, no reversing takes place;因此,不会发生逆转; if you are selecting data from the table again and these rows come back in a reverse order, then that's a coincidence and not a choice the database made.如果您再次从表中选择数据并且这些行以相反的顺序返回,那么这是巧合,而不是数据库做出的选择。

If rows must come back in a specific order, use ORDER BY when selecting.如果行必须以特定顺序返回,请在选择时使用ORDER BY You could order by ROWID for example, which may be increasing monotonically for new rows and thus give you an approximation for insertion order.例如,您可以按ROWID排序,这可能会为新行单调增加,从而为您提供插入顺序的近似值。 See ROWIDs and the INTEGER PRIMARY KEY .请参阅ROWID 和 INTEGER PRIMARY KEY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM