【问题标题】:Date search in sqlite not workingsqlite中的日期搜索不起作用
【发布时间】:2015-04-27 11:51:24
【问题描述】:

我正在尝试在数据库中搜索明天的日期,然后转到电子邮件功能。

def send_email():
currentdate = time.strftime("%d/%m/%Y")
nextday = datetime.date.today() + datetime.timedelta(days=1)
tomorrow = str(nextday.strftime("%d %m %Y"))
with sqlite3.connect("school.db") as db:
    cursor = db.cursor()
    cursor.execute("SELECT DateIn FROM MusicLoan WHERE DateIn = ?",(tomorrow,))
    row = cursor.fetchall()[0]
    if str(row) == str(tomorrow):
        cursor.execute("SELECT StudentID FROM MusicLoan WHERE DateIn = ?", (currentdate))
        ID = cursor.fetcone()[0]
        cursor.execute("SELECT email FROM Student WHERE StudentID = ?",(ID))
        email = cursor.fetchone()[0]
        fromaddr = email
        toaddr = "danielarif@blueyonder.co.uk"
        msg = MIMEMultipart()
        msg['From'] = fromaddr
        msg['To'] = toaddr
        msg['Subject'] = "Music Reminder"
        body = "A reminder that your music is due in tomorrow"
        msg.attach(MIMEText(body, 'plain'))
        try:
            server = smtplib.SMTP('smtp.gmail.com', 587)
            server.ehlo()
            server.set_debuglevel(1)
            server.starttls()
            server.ehlo()
            server.login("danielarif123@gmail.com", "DanR0bJ0nes3")
            text = msg.as_string()
            server.sendmail(fromaddr, toaddr, text)
            server.quit()
            print("Email Sent Successfully")
            send_email()
        except smtplib.SMTPException:
            print ("Error: unable to send email")
            send_email()

我的问题是它到达 row = cursor.fetchall()[0] 然后停止。 我该如何解决这个问题

【问题讨论】:

    标签: python sql database sqlite datetime


    【解决方案1】:

    它不会“停止”,它会到达下一行的 if 条件,因为它永远不会为真,所以它一直到最后。

    fetchall() 将为您提供一个元组列表,即匹配的所有行的列表,其中每一行都是所有列的元组。因此,您的 [0] 索引实际上为您提供了一个具有单个元素的元组,即数据列。但str(row) 将类似于('2015-04-29',),不等于'2015-04-29'

    您需要迭代来自 fetchall() 的结果,然后检查每一行。

    但这仍然不能解决您的问题,因为您有更深层次的逻辑错误。您选择 DateIn 等于明天的行。但随后您检查 DateIn 是否等于 today。再说一次,这永远不会是真的。

    【讨论】:

    • 我没有注意到那里的逻辑错误,我写得这么快就不好了。现在已经编辑过了。如何迭代这些结果?
    • 使用 for 循环:for row in cursor.fetchall(),然后是 if row[0] == str(tomorrow),尽管您修改后的代码永远不会是错误的。
    • 另外,您可能想更改您的 GMail 密码,现在您已在 Internet 上公开发布...
    • 哦,那是我以前的 gmail
    【解决方案2】:

    cursor.execute("SELECT DateIn FROM MusicLoan WHERE DateIn = ?",(tomorrow,))

    并使用 fetch 一种方法 cursor.fetchone()

    更多示例请参考https://docs.python.org/2/library/sqlite3.html

    【讨论】:

    • 如果我这样做,我会得到这个错误 cursor.execute("SELECT DateIn FROM MusicLoan WHERE DateIn= ?",(tomorrow)) sqlite3.ProgrammingError: Incorrect number of bindings provided。当前语句使用 1,提供了 10 个。
    猜你喜欢
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 2018-06-23
    相关资源
    最近更新 更多