0

I have the fallowing code which aim is to extract some sensor data and insert in to a MySQL database.

def sendDataToDB(con, data, table):
    cur = con.cursor()
    cur.execute("INSERT INTO %s (`sensor_id`, `value`, `unit`, `datetime`) VALUES (%s, %s, %s, %s)", (table, data.uuid, data.value, data.unit, data.datetime))
    con.commit()

temperatureSens = TemperatureSensor(0, 'temperature', 'celsius')
con = connector.Connect(user = db_user_name, password = db_password, database = db_name, host = db_host, port = db_port)

temp = temperatureSens.extractData()
print(temp.uuid, temp.value, temp.unit, temp.datetime)
sendDataToDB(con, temp, 'temperature_data')

The data is extracted correctly(this is the purpose of the print statement) but i have an error in the syntax of the INSERT query which i really cant find. There is the error:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server version for
the right syntax to use near ''temperature_data' ('sensor_id', 'value', 'unit',
'datetime') VALUES (0, 23.0, '' at line 1

I'm sure that the problem is in the python syntax(which i'm nor very fimilar with) but i can't find it.
Thank you in advice.

EDIT** the root cause issue is that it is messed up (`) sign with (') in the INSERT query.

2 Answers2

1

As Lukasz Szozda said table name can not be a parameter,see Table name as variable,also you need add ' to wrap %s,so change

 cur.execute("INSERT INTO %s (`sensor_id`, `value`, `unit`, `datetime`)
 VALUES (%s, %s, %s, %s)",
 (table, data.uuid, data.value, data.unit, data.datetime))

To

cur.execute("INSERT INTO youtable (`sensor_id`, `value`, `unit`, `datetime`) 
VALUES ('%s', '%s', '%s', '%s')",
(data.uuid, data.value, data.unit, data.datetime))
lucumt
  • 6,642
  • 2
  • 16
  • 32
0

I have encounter same problem, finally found the root cause is:

the datetime value should be string -> wrap by quote, like "datetime_value" or 'datetime_value'

so, should your code:

cur.execute("INSERT INTO %s (`sensor_id`, `value`, `unit`, `datetime`) VALUES (%s, %s, %s, %s)", (table, data.uuid, data.value, data.unit, data.datetime))

which datetime value is like 2019-01-02 15:08:59.490163

should change to:

cur.execute("INSERT INTO %s (`sensor_id`, `value`, `unit`, `datetime`) VALUES (%s, %s, %s, '%s')", (table, data.uuid, data.value, data.unit, data.datetime))

which datetime value is like '2019-01-02 15:08:59.490163'

and better change to, use backtick for tablename:

cur.execute("INSERT INTO `%s` (`sensor_id`, `value`, `unit`, `datetime`) VALUES (%s, %s, %s, '%s')", (table, data.uuid, data.value, data.unit, data.datetime))
crifan
  • 8,424
  • 1
  • 45
  • 35