首页 > 解决方案 > 订购 SQL 数据库

问题描述

我已经开始在 Python 3.7.6 中编写 SQL 并开始创建一个“备忘单”,一切都很顺利,直到我尝试订购它(我在这里使用的示例是订购数据库“database1”,工作表名称“test1” ”)。我已经在网上阅读并看到人们使用该代码:

SELECT * FROM test1
ORDER BY fname

这似乎可行,但我遇到的问题是它似乎没有以这种有序的形式保存数据库,这是我想要实现的(文件根本没有改变;修改的时间没有' t 改变)。我见过其他人附加代码,所以我会在最后写下相关部分。

def order(fileName, sheet, attributes, condition, ascencion):
    connection = sqlite3.connect(fileName+".db")
    cursor = connection.cursor()
    sql_command = """SELECT *
FROM """ + str(sheet) + "\n"
    sql_command += "ORDER BY "  + str(attributes[0][0])
    if ascencion.lower() == "increasing" or ascencion.lower() == "ascending":
        sql_command += " ASC;"
    elif ascencion.lower() == "decreasing" or ascension.lower() == "descending":
        sql_command += " DESC;"

    cursor.execute(sql_command)
    connection.commit()
    connection.close()

标签: pythonsqlsqlite

解决方案


SQL 表表示无序集。你真的不应该认为有任何排序,除非你指定排序。

order by因此,只需使用该子句检索数据。

也就是说,SQLite 是一个基于文件的数据库,因此无论查询如何,它都可能确实保留了文件中的顺序。但是,由于 SQL 通常不会以这种方式运行,因此我建议您不要依赖它。

相反,声明fname为表上的主键或使用fname. 您仍然需要order by,但使用这些方法应该几乎没有开销


推荐阅读