2016-05-30 64 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