2017-08-21 27 views
-1

我想比較局部變量SQLITE3如何快速高效地查詢此?

currentTime = time.time() 

數據在我的表中,列的AuthorID下,看哪個值更大。然後,我將着手將'Reminded'列更新爲True。我的表格叫做reminderFormat。

這是數據庫的樣子:http://prntscr.com/gb9ay1

什麼是去了解這一點的最好方法是什麼?我相信我可以專門讀取FutureTime並將其存儲爲變量,然後將其與currentTime進行比較。但是,對於使用查詢更快,更高效的方法,是否會有更好的選擇?

感謝

+0

請參閱[如何在堆棧溢出文章中格式化SQL表?](https://meta.stackexchange.com/q/96125) –

回答

1

我認爲,最好的做法是使用單個SQL語句來更新記錄。

因爲,SQLite has no boolean value,您需要設置值(而不是True)。

例如,聲明可能是:

import time 

st = "UPDATE reminderFormat SET Reminded = 1 " \ 
    "WHERE FutureTime <= {currentTime}".format(currentTime=time.time()) 

編輯:演示

這裏是一個演示:

import time 
import sqlite3 

records = [ 
    (20183740995, 1503330725.0, "testtt", 0), 
    (20183740995, 1503330732.0, "testtt", 0), 
    (20183740995, 1503331334.0, "testtt", 0), 
    (20183740995, 1509999999.0, "testtt", 0), 
    ] 

con = sqlite3.connect(":memory:") 

# Create the table 
con.execute("create table reminderFormat(AuthorID, FutureTime, Message, Reminded)") 

# Fill the table 
con.executemany("INSERT INTO reminderFormat(AuthorID, FutureTime, Message, Reminded) VALUES (?, ?, ?, ?)", records) 

curr_time = time.time() 
con.execute("UPDATE reminderFormat SET Reminded = 1 WHERE FutureTime <= ?", (curr_time,)) 

# Print the table contents 
for row in con.execute("SELECT AuthorID, FutureTime, Reminded FROM reminderFormat"): 
    print(row) 

你得到:

(20183740995, 1503330725.0, 1) 
(20183740995, 1503330732.0, 1) 
(20183740995, 1503331334.0, 1) 
(20183740995, 1509999999.0, 0) 
+0

請參見[如何在Python中使用SQL語句中的變量?](https:// stackoverflow。 com/questions/902408/how-to-use-variables-in-sql-statement-in-python) –

+0

@CL:同意,但我不知道哪個客戶端庫使用了OP,所以... –

+0

謝謝,更新結果 – smye

-2

在sqlite3的,你可以使用Case語句查詢來檢查,如果您的當前時間比AuthorID此您在sqlite3的查詢小於或大於將是這樣的:

select case AuthorID<Futuretime then 1 else 0 end from table; 

這應該爲您提供10列,而無需獲取python時間。