无法从MySQLdb数据库中获取数据

时间:2016-05-30 12:22:44

标签: python sqlite arduino raspberry-pi3

[在此处输入图片说明] [1]我目前正在为学校制作一个项目,并且到达隔离墙的时间已到了。

我正在尝试从Raspberry Pi 3+上的USB端口获取数据。我连接了一个Arduino Nano,我通过USB端口发送一个字符串(RFID卡的十进制UID号)到Pi。这里一切正常,我可以打印出字符串(ID)没有问题。我正在将卡中的ID与我的数据库中的ID进行比较,如果我输入一个静态数字(在下面的代码中注释),它会打印数据。但是,如果我尝试使用串行线路,则没有任何反应。它似乎根本不能获取数据。我的数据库的前景在下面,也是python代码。 提前致谢 !!

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

#!/ usr / bin / env python

 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/

1 个答案:

答案 0 :(得分: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 DB中,并且还处理了异常,因此你可以找出运行时错误,如果有的话!