0

Using pyserial, I am getting data from a sensor plugged into the USB port. I am trying to store that data, using MYSQLdb, into a database.

cur = db.cursor() 
cur.execute("TRUNCATE TABLE randomdata;")

if ser.isOpen():
    try:
        i = 1
        while 1:
            num = str(1)
            readserial = ser.readline()
            print readserial
            query="INSERT INTO randomdata(id,randomString)VALUES("+num+",'"+readserial+"');"
            cur.execute(query)
            db.commit()
            i+=1
            time.sleep(2)

            if (i >= 50):
                break
        ser.close()
    except Exception, e1:
        print "error communicating...: " + str(e1)
else:
    print "cannot open serial port "

It will store one value in the database before showing the error message: "error communicating...: (1062, "Duplicate entry '1' for key 'PRIMARY'")"

Any help would be greatly appreciated.

4

2 回答 2

1

You cannot insert twice a value with the same id.

Here your id is "1" each time.

Depending on what you want to do you will need to use UPDATE instead of INSERT if you want to keep always the same id (and thus keep only one value). Something like that (untested) :

"UPDATE randomdata SET randomString = " + readserial +" WHERE id = " + num

Or you want to store all your value and insert new entry each time, then you need to generate a new id each time (by using your i instead of 1 in the while loop).

于 2013-11-07T14:39:29.563 回答
1
num = str(1)

which means num is always 1.

query="INSERT INTO randomdata(id,randomString)VALUES("+num+",'"+readserial+"');"

You insert 1 which is num as the ID at each time which is your primary key. Then, you got the error.

Why don't you use i instead like this :

num = str(i)

Since you increase i, the ID will not be duplicated.

于 2013-11-07T14:41:56.833 回答