2016-09-16 73 views
2

我想從我有一個數據庫中獲取信息。但是每次我搜索它時,都說沒有任何東西在查詢之後。這是我的。我在MySQL搜索它不工作(Python)

import datetime 
import MySQLdb 

db = MySQLdb.connect(user='root', passwd='', host='localhost', db = 'data') or die ('Error while connecting') 
cursor = db.cursor() 
sqlread = "SELECT * FROM humidity WHERE Date_Hour BETWEEN %s AND %s" 

ts1 = ('%s/%s/%s 07:00:00') % (now.year, now.month, now.day) 
ts2 = ('%s/%s/%s 03:00:00') % (now.year, now.month, now.day+1) 

tsdata = (ts1,ts2) 
cursor.excecute(sqlread,tsdata) 
db.commit() 
result = cursor.fetchall() 
print result 

因此,結果爲0.但是我對phpMyAdmin進行了相同的搜索,結果如下。我做錯了什麼?

UPDATE:

這裏是我的結果作爲賈森評論。 enter image description here 不過,我認爲傑森是對的。我正在做一些圖表的GUI。我有2個窗戶。一種是使用matplotlib製作一個帶有動畫的圖形,該程序使圖形具有從數據庫中回收的新數據,因此它總是在問。另一個窗口只是一個查詢,但它不起作用,所以這可能是可能的,因爲我問「兩次」?

回答

1

您的db.commit()可能會丟掉它。但是,有很多因素可以參與其中。您也可以考慮打印出你的SQL查詢來查看被放那麼這樣的:

嘗試設置你這樣的代碼,它應該引領你在正確的方向:

import MySQLdb as mdb 
conn = mdb.connect('localhost', 'user', 'password', 'database_name') 
try: 
    cur = conn.cursor() 
    ts1 = ('%s/%s/%s 07:00:00') % (now.year, now.month, now.day) 
    ts2 = ('%s/%s/%s 03:00:00') % (now.year, now.month, now.day + 1) 
    sqlread = "SELECT * FROM my_table where blah between {} and {}".format(ts1, ts2) 
    print(sqlread) 
    cur.execute(sqlread) 
    res = cur.fetchall() 
except mdb.Error as e: 
    pass 
finally: 
    if conn: 
     conn.close() 
+0

嗨傑森,謝謝爲你的時間。我更新了我的帖子,也許你是對的。 –

+0

@AjjandroHarrisBonet您的日期如何存儲在數據庫中?它是否與 - 或/?如果將日期更改爲年 - 月 - 日而不是年/月/日,會發生什麼? – CodeLikeBeaker

+0

嗨賈森,其實我把它保存爲一個字符串。 YYYY/MM/DD,我不知道我是否應該將它作爲DATETIME格式,因爲在嘗試從數據庫中收集日期之前,我遇到了一些問題。 –