sqlite 在查询中使用参数在日期之间搜索

hwamh0ep  于 2022-12-04  发布在  SQLite
关注(0)|答案(2)|浏览(126)

愚蠢的新来的。所以我在这里敲我的头:无法确定参数化查询以及其格式是否正确。

import sqlite3

def readSqliteTable():
    try:
        sqliteConnection = sqlite3.connect('testDB.sqlite')
        cursor = sqliteConnection.cursor()
        print("Connected to SQLite")
        startdate = "2022-11-05"
        enddate = "2022-11-25"
        print("startdate =", startdate, "enddate =", enddate)
        cursor.execute("SELECT * FROM tz WHERE UL_Time BETWEEN '%s' AND '%s'" % (startdate, enddate))
        print(cursor.fetchall())
        records = cursor.fetchall()
        print("Total rows are:  ", len(records))
        print("Printing each row")
        for row in records:
            print("Id: ", row[0])
            print("Updated: ", row[1])
            print("Title: ", row[2])
            print("UL_Time: ", row[3])
            print("Size: ", row[4])
            print("\n")

        cursor.close()

    except sqlite3.Error as error:
        print("Failed to read data from sqlite table", error)
    finally:
        if sqliteConnection:
            sqliteConnection.close()
            print("The SQLite connection is closed")

如果我将任意日期替换为以下内容,它将正常工作:

cursor.execute("SELECT * FROM tz WHERE UL_Time BETWEEN 2022-11-01 AND 2022-11-25")

但在这种形式下不起作用

xeufq47z

xeufq47z1#

首先,你不了解什么是参数化查询,阅读Python的官方文档和教程。
你的表情

"SELECT * FROM tz WHERE UL_Time BETWEEN '%s' AND '%s'" % (startdate, enddate))

显示字符串插值,与参数化查询无关。此查询还实现了文本筛选器。只要您的所有日期格式都为YYYY-MM-DD,它就可以正常工作。
第二个查询没有意义,因为WHERE子句定义了一个整数筛选器:

WHERE UL_Time BETWEEN 2010 AND 1986
fd3cxomn

fd3cxomn2#

明白了。我在startdate和enddate两个变量的初始化格式上犯了一个错误,在year和month之间加了一个连字符。我在第二个查询中看到了我愚蠢的算术计算。有时候你必须用另一个来指出你显而易见的东西。
谢谢你!

相关问题