How to insert object to mysql using python?
Question: I write code to read RFID tag using python, check the existence of the ID in
the database. If successful, right ID on database led is ON, but command
insert to database not work. Python gives no error message, and I do not
understand what's wrong with it.

How can I fix it? Please help me.

Thank you very much.

Here is my code:

    
    
    import serial
    import time
    import RPi.GPIO as GPIO
    import MySQLdb
    from datetime import datetime
    from binascii import hexlify
    serial=serial.Serial("/dev/ttyAMA0",                    
                          baudrate=9600,                     
                          parity=serial.PARITY_NONE,                    
                          stopbits=serial.STOPBITS_ONE,                    
                          bytesize=serial.EIGHTBITS,
                          timeout=0.1) 
    GPIO.setmode(GPIO.BOARD) 
    GPIO.setup(12, GPIO.OUT)
    chuoi= "\xAA\x00\x03\x25\x26\x00\x00\xBB"
    db = MySQLdb.connect(host='localhost', user='root', passwd='root', db='ex_1')
    cur = db.cursor(MySQLdb.cursors.DictCursor)
    while 1:   
        serial.write(chuoi)      
        data =serial.readline()    
        tach = data[5:8]    
        hex = hexlify(tach)   
        num = int(hex,16)    
        print(num)      
        cur.execute("SELECT * FROM thong_tin WHERE Card_ID = '%d'" %num)    
        rows = cur.fetchall()    
        for row in rows:    
                ID = row['Card_ID']     
                if( num == ID):     
                         GPIO.output(12, True)
                        cur.execute("INSERT INTO data (Card_ID,Time_out,Time_in) VALUES ('%d',NOW(),NOW())" %num) #-> it does not add to database   
                        time.sleep(3)       
                        GPIO.output(12, False);     
                else:       
                        GPIO.output(12, False);
    


Answer: At first you have a indentation error in your code:

    
    
            if( num == ID):     
                     GPIO.output(12, True)
                    cur.execute("INSERT INTO data (Card_ID,Time_out,Time_in) VALUES ('%d',NOW(),NOW())" %num) #-> it does not add to database   
                    time.sleep(3)       
                    GPIO.output(12, False);
    

One line is indented more than the others.

Also you do not have to use ; at the end of the line in Python. And you should
not use the normal string formating with DB queries for security reason (SQL
injections). From the MySQLdb User's Guide:

    
    
    c.execute("""SELECT spam, eggs, sausage FROM breakfast
          WHERE price < %s""", (max_price,))
    

This form will automatically quote the values in a safe way.

