0

I would like to have the SQL SYNTAX INSERT code to be dynamic for which table to insert data into. When I try the code below I get SYNTAX error, probably due to that it adds '-marks around the table. How can I solve this?

system=str(event['system'])
value1=str(event['value1'])
value2=str(event['value2'])
timestamp=str(event['timestamp'])
table=str('table1')    

insert_stmt = ("INSERT INTO %s (system, value1, value2, timestamp) ""VALUES (%s, %s, %s, %s)")
data = (table, system, value1, value2, timestamp)
cur.execute(insert_stmt, data)
conn.commit()

My Error:

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 ''table1' (system, value1, value2, timestamp) VALUES ('qwerty', '1', '1',' at line 1\")", "errorType": "ProgrammingError",

0

1 Answer 1

0

You use reserved keywords as fieldname timestamp. You can only use it if you put it in backticks like:

 insert_stmt = ("INSERT INTO %s (system, value1, value2, `timestamp`) ""VALUES (%s, %s, %s, %s)")
data = (table, system, value1, value2, timestamp)

But make your live easier! Dont use KEYWORDS as fieldname !!!

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! That is a good valid point. I will change that. But I dont' think that's the cause for my error.
if it not or not only your error. please output the generated query and post it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.