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

Failing to fetch data from MySQLdb database

[在此处输入图片描述][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/

可能的解决方案是:

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 中,并且还处理了异常,以便您可以找出运行时错误(如果有的话)!