2015-04-27 60 views
0

我想搜索數據庫的明天日期,然後進入電子郵件功能。在sqlite中的日期搜索不起作用

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 = "[email protected]" 
     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("[email protected]", "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() 

我的問題是,它得到行= cursor.fetchall()[0],然後停止。 我該如何解決這個問題

回答

0

它不會「停止」,它會到達下一行的if條件,並且因爲它永遠不會成立,它會一直到最後。

fetchall()會給你一個元組列表,這是所有行匹配的列表,每行都是所有列的元組。因此,您的[0]索引實際上爲您提供了一個元素(數據列)。但是str(row)將類似('2015-04-29',),這不等於'2015-04-29'

您需要迭代來自fetchall()的結果,並檢查每個行。

但是,這仍然不能解決您的問題,因爲你有更深的邏輯錯誤。您選擇DateIn等於明天的行。但是你再檢查DateIn等於今天。再一次,這永遠不會是真的。

+0

我沒有注意到那裏的邏輯錯誤,我很快寫下這個錯誤。它已被編輯。 如何迭代這些結果? –

+0

使用for循環:'for cursor in cursor.fetchall()',然後'if row [0] == str(tomorrow)',儘管修改過的代碼永遠不會是錯誤的。 –

+0

改變了一些東西,現在它的工作原理,謝謝:) –

-1

cursor.execute( 「選擇DateIn FROM MusicLoan WHERE DateIn =?」,(明天))

,並使用提取的一種方法cursor.fetchone()

請參https://docs.python.org/2/library/sqlite3.html更多的例子

+0

如果我那麼,我得到這個錯誤 cursor.execute(「SELECT DateIn FROM MusicLoan WHERE DateIn =?」,(明天))sqlite3.ProgrammingError:提供的綁定數量不正確。當前的語句使用1,並提供了10個。 –