from datetime import datetime
import pyodbc
import msvcrt # Note: Change to getch on non-Windows systems.

# Start the connection to the Access DB. ******** Adapt the path after DBQ according to your needs. ********
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\temp\Access\RFID_Database_be.accdb;')
# Get a connection cursor.
cursor = conn.cursor()
# Now wait forever on keyboard sequences - just until anybody presses "q".
keepRunning = True
cardID = ""
while keepRunning:
    char = msvcrt.getch()
    if char == b'q':
        keepRunning = False # Terminate the program using the 'Q' key.
    elif char == b'\n':
        None # In most cases, the readers send both '\n', and 'r'. We skip the '\n'.
    elif char == b'\r':
        print(cardID)
        # If receiving the system sporadically misses single digits from the reader, 
        # or if any other problems can occur, add code for checking the ID here.
        # *******************
        # Go on sending the code to the database now.
        # Create SQL query.
        now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        query = "INSERT INTO RFID_Codes (CardID, StampTime) VALUES (%s, '%s')" % (cardID, now)
        print(query)
        # Add the new record to the database...
        cursor.execute(query)
        # ...and make it persistent.
        conn.commit()   
        cardID = ""
    else:
        cardID = cardID + char.decode("utf-8")
## The following lines print the entire contents of the database table. This can be used for debgging.
#cursor.execute('select * from RFID_Codes')
#for row in cursor.fetchall():
#   print (row)
cursor.close()
conn.close()