I want to save the sensor value as strquery in mysql with Python, but how can I solve the problem that only '0' is stored in mysql although the sensor value is output from the terminal?

Asked 2 years ago, Updated 2 years ago, 73 views

The sensor value measured by Arduino is sent to Raspberry Pi via Bluetooth, and Raspberry Pi receives the sensor value by Python and tries to save it in mysql. As mentioned in the question, when you run the python file on the terminal, the terminal outputs a sensor value normally, but if you connect to localhost/phpmyadmin in Chrome and check the stored database, it is only saved to 0. What's the problem? The following is the Python code:

import bluetooth

import MySQLdb

bd_addr="00:21:13:01:5B:65"

port=1

sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)

sock.connect((bd_addr,port))

data=""

db=MySQLdb.connect("localhost", "root", "1234", "testdb")

curs=db.cursor()

print 'Start Monitor'

while 1:

try:
    data +=sock.recv(1024)
    data_end=data.find('\n')
    if data_end!=-1:
        rec=data[:data_end+1:]
        print data
        data=data[data_end+1:]
        strQuery="INSERT INTO weight (kg) VALUES('+data')"
        curs.execute(strQuery,)
        db.commit()
except KeyboardInterrupt:
    break

sock.close() db.close()

And there is an error in the terminal as follows

Warning: Incorrect double value: '+ data ' for column 'kg' at row 1 curs.execute(strQuery)

python bluetooth mysql strquery raspberry-pi

2022-09-22 21:08

1 Answers

strQuery="INSERT INTO weight (kg) VALUES('+data')"

The string didn't close properly. " If you open it with ", you have to close it with ".
String connection operator + is also missing one.

strQuery="INSERT INTO weight (kg) VALUES(" + data + ")"

I think we can modify it as above.


2022-09-22 21:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.