2016-05-30 63 views
0

[目前我正在爲一所學校開展一個項目,並且到達城牆的時間已經到來。未能從MySQLdb數據庫中提取數據

我想從Raspberry Pi 3 +上的USB端口獲取數據。我已經連接了一個Arduino Nano,並且我通過USB端口向Pi發送了一個字符串(RFID卡的十進制UID號)。在這裏一切正常,我可以打印出沒有問題的字符串(ID)。我將卡上的ID與數據庫中的ID進行比較,如果我將一個靜態數字(在代碼中註釋如下)打印出數據。但是,如果我嘗試使用串行線,則什麼也不會發生。它好像根本不提取數據。我的數據庫的前景以及python代碼。 在此先感謝! !

card_id serial_no LastName FirstName 
    1 | 2136106133 | Hansen | Peter  | 
    2 | 117254270 | Larsen | Thompson | 

#的/ usr/bin中/ env的蟒

import MySQLdb 
import serial 


ser = serial.Serial('/dev/ttyUSB0',9600) 
db = MySQLdb.connect(host="localhost", # your host, usually localhost 
       user="root",   # your username 
       passwd="root", # your password 
       db="RFID")  # name of the data base 
cur=db.cursor() 

CardID = 0 
LastName = "" 
FirstName = "" 

while True: 
    CardID=ser.readline() 

    print "pweasda" 
    print CardID 
    print "pewpew" 
    # CardID = 117254270 - this works. The problem is that I have many RFID cards/tags with different IDs of course. With this statement it prints everything correctly. 

    cur.execute('SELECT * FROM cards WHERE serial_no=%s',(CardID)) 
    results = cur.fetchall() 
    for row in results: 
     FirstName = row[3] 
     LastName = row [2] 
     serial_no = row [1] 
     card_id = row [0] 
     #print the fetched results 
     print "FirstName=%s,LastName=%s,serial_no=%s,card_id=%s" % \ 
     (FirstName, LastName, serial_no, card_id) 
     db.commit() 
     print "Data committed" 

輸出圖像(沒有錯誤):[1]:http://postimg.org/image/jf2doogrv/

+0

你的數據庫是MySql還是sqlite? –

+0

正如你可以在我的python代碼的開頭看到它說的導入MySQLdb。不過,我也嘗試過使用sqlite3。同樣的結果 – Smesh

+0

不,以上代碼只能用於mysql! –

回答

0

可能的解決方案可以是:

import sqlite3 
conn = sqlite3.connect("users.db")#path to your sqlite db file! 
cursor = conn.cursor() 
CardID=ser.readline().strip() 


sql = "SELECT * FROM cards WHERE serial_no=?" 
cursor.execute(sql, [(CardID)]) 
try: 
    results = cursor.fetchall()[0]# just fetching the first row only, you can loop through all rows here! 
    FirstName = results[3] 
    LastName = results[2] 
    serial_no = results[1] 
    card_id = results[0] 
    print "FirstName=%s,LastName=%s,serial_no=%s,card_id=%s" % \ 
    (FirstName, LastName, serial_no, card_id) 

except IndexError as e: 
    print 'CardID Not Exist'+str(e) 
except Exception as e2: 
    print(str(e2)) 

在上面的代碼中,我假設數據庫是在sqlite數據庫中,並且還處理了異常,因此您可以計算出運行時錯誤,如果有的話!

+0

謝謝,我現在就試試。 – Smesh

+0

實際上,從你的截圖中,你在where子句中使用錯誤的CardID,它不在db中,所以最終它不會進入for循環,否則你的代碼是正確的! –

+0

是的,我的壞 - 不同的卡。仍然無法使用正確的ID。所以它給了我以下結果:CardID不存在 - 索引超出範圍(您的解決方案) – Smesh